Angular 2如何让我的变量等待值的异步?

时间:2016-07-08 10:06:01

标签: angular

我有这个错误:

  

TypeError:无法在PaginationComponent.ngOnChanges(pagination.component.ts:38)中读取未定义的属性'length'

这是我的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);
}

我在另一个组件AboutUsComponent中使用它的方式:

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

帖子加载在AboutUsComponent:

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

据我所知,这是因为帖子的.subscribe()异步加载和@Input() items = [];可能会在帖子到来之前加载。 我怎样才能让它等待或者您建议过度解决方案? 谢谢。

1 个答案:

答案 0 :(得分:0)

您可以检查ngChanges方法的参数,以确保更改与items相对应。这样,您就可以确定items输入已设置:

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

即使在ngOnChanges输入...

上,每次更改都会调用pageSize方法