简体   繁体   English

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

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

I have this error : 我有这个错误:

TypeError: Cannot read property 'length' of undefined at PaginationComponent.ngOnChanges (pagination.component.ts:38) TypeError:无法读取PaginationComponent.ngOnChanges(pagination.component.ts:38)上未定义的属性“长度”

This is my PaginationComponent : 这是我的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);
}

This how I am using it in another component AboutUsComponent : 这就是我在另一个组件AboutUsComponent使用它的AboutUsComponent

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

And the posts are loaded in AboutUsComponent: 帖子被加载到AboutUsComponent中:

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

As I understand it happens because of .subscribe() async loading of posts and @Input() items = []; 据我了解,发生这种情况是由于帖子的.subscribe()异步加载和@Input() items = []; could be loaded before posts come. 可以在帖子来之前加载。 How can I make it await or what over solution may you suggest? 我应该如何等待它,或者您可能提出什么解决方案? Thank you. 谢谢。

You could check the parameter of the ngChanges method to be sure that the changes correspond to items . 您可以检查ngChanges方法的参数,以确保更改与items相对应。 This way, you would be sure that the items input is set: 这样,您将确保设置了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);
    }
  }
}

The ngOnChanges method is called for every change even on the pageSize input... 即使在pageSize输入上,每次更改也会调用ngOnChanges方法。

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

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