我有一个错误:
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中使用它的方式。
<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()异步加载了posts,而@Input() items = [];可以在发布之前加载。我怎样才能让它等待,或者你可以提出什么解决方案?谢谢。
发布于 2016-07-08 10:12:21
您可以检查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输入上也是如此.
https://stackoverflow.com/questions/38263983
复制相似问题