Search code examples
javascriptangulartypescriptngx-gallery

failed to update variable n after returning the collection of values in angular


I am facing an annoying problem. before returning the collection of values in ts file I updated my n values for expect for n=0 (for (let i=n) for display all postedpics(Image) for n=1 for display all postedpics and so on. but after returning, I notice n variable is not updated and for that continuously displaying only for n=0's all postedpics. here is the code:-

component.ts

...
  ngOnInit(): void {
     this.galleryPosts = this.getPosts();
    
  }
...

 n:number=0;

  getPosts(): NgxGalleryImage[] {
    const postUrls = [];
    for (let i = this.n; i < this.member.posts.length ; i++) {
         const post = this.member.posts[i];
        for(let j=0; j < post.postedpics.length;j++)
        {
          postUrls.push({
            small: post.postedpics[j]?.url,
            medium: post.postedpics[j]?.url,
            big: post.postedpics[j]?.url
          })

        }
        this.n++;
        return postUrls;
       
    }
}

component.html

<div *ngFor="let m of member.posts">
  <p>{{m.description}}</p>
  <p  *ngFor="let s of m.postedpics">{{s.url}}</p>
  <ngx-gallery class="mt-4" [options]="galleryOptions" [images]="galleryPosts"
               style="display: inline-block; margin-bottom: 20px;"></ngx-gallery>
</div>

when I run, then I found only for n=0's all postedpics but I expect for n=0, n=1, n=2's postedpics. I am an absolute beginner. please help.


Solution

  • You can update it following way to check whether its working fine or not.

    getPosts(): NgxGalleryImage[] {
        const postUrls = [];
        for (let i = this.n; i < this.member.posts.length; i++) {
                const post = this.member.posts[i];
                for (let j = 0; j < post.postedpics.length; j++) {
                        postUrls.push({
                                small: post.postedpics[j]?.url,
                                medium: post.postedpics[j]?.url,
                                big: post.postedpics[j]?.url
                        })
    
                }
                this.n++;
    
        }
        return postUrls;
    

    }

    if you check your code, you are returning posturls after first iteration only.