简体   繁体   中英

Angular 2 how can i make my variable wait async for values?

I have this error :

TypeError: Cannot read property 'length' of undefined at PaginationComponent.ngOnChanges (pagination.component.ts:38)

This is my PaginationComponent :

@Input() items = [];
@Input('page-size') pageSize;
@Output('page-changed') pageChanged = new EventEmitter();
pages: any[];
currentPage; 
public numberofpages = 10;
ngOnChanges(){
    this.currentPage = 1;
    var pagesCount = this.items.length / this.pageSize; 
    this.pages = [];
    for (var i = 1; i <= pagesCount; i++)
        this.pages.push(i);
}

This how I am using it in another component AboutUsComponent :

<pagination [items]="posts" [page-size]="pageSize" (page-changed)="onPageChanged($event)"></pagination>

And the posts are loaded in AboutUsComponent:

private loadPosts(){
    this.postsLoading = true;
    this._aboutusService.getPosts().subscribe( 
        posts => {this.posts = posts;
                  this.pagedPosts = this.getPostsInPage(1)}, 
        null, 
        () => { this.postsLoading = false});
}

As I understand it happens because of .subscribe() async loading of posts and @Input() items = []; could be loaded before posts come. How can I make it await or what over solution may you suggest? Thank you.

You could check the parameter of the ngChanges method to be sure that the changes correspond to items . This way, you would be sure that the items input is set:

ngOnChanges(changes: SimpleChanges){
  if (changes['items']) { // <----
    this.currentPage = 1;
    var pagesCount = this.items.length / this.pageSize; 
    this.pages = [];
    for (var i = 1; i <= pagesCount; i++)
      this.pages.push(i);
    }
  }
}

The ngOnChanges method is called for every change even on the pageSize input...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM