[英]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.