繁体   English   中英

Angular 2如何使变量等待异步值?

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

我有这个错误:

TypeError:无法读取PaginationComponent.ngOnChanges(pagination.component.ts:38)上未定义的属性“长度”

这是我的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使用它的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 = []; 可以在帖子来之前加载。 我应该如何等待它,或者您可能提出什么解决方案? 谢谢。

您可以检查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);
    }
  }
}

即使在pageSize输入上,每次更改也会调用ngOnChanges方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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