Home > front end >  TypeError: this.c[i] is undefined
TypeError: this.c[i] is undefined

Time:11-30

I am actually trying to show photos using NgxGallery. but when i run the code i found an unexpected error in console. I am using Angular Version 12. here is my code:-

member.component.ts

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

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

        }
        this.n  ;
        return postUrls;
    }
}

member.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  [options]="galleryOptions" [images]="galleryPosts" 
                        style="display: inline-block; margin-bottom: 20px;"></ngx-gallery>
                </div>

here is the error:-

ERROR TypeError: this.c[i] is undefined
    Ember 2
    RxJS 20
    Angular 17
    RxJS 8
    Angular 17
    RxJS 22

For alternative I tried <ngx-gallery [options]="galleryOptions" [images]="small:s.url;medium:s.url;big:s.url" style="display: inline-block; margin-bottom: 20px;"></ngx-gallery> but found a lot errors. it's ok.

My actual intention is how i resolve this c[i] is undifined issue, also Image not displayed as expected. I don't understand. I am an absolute beginner. please help.

CodePudding user response:

Try not to use properties as local variables, this gets confusing (this is living proof!)

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;
    }
}

See, I've changed that c to post and it made it clear that there was a confusion in your code... Does this look better?

  • Related