我有这个错误:
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 = [];
可能会在帖子到来之前加载。
我怎样才能让它等待或者您建议过度解决方案?
谢谢。
答案 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
方法