簡體   English   中英

如何枚舉Angular 2中從Observable Subscription返回的數據?

[英]How to enumerate data returned from Observable Subscription in Angular 2?

我具有有關可觀察性工作原理的基本思想,我可以通過調用subscription方法並在模板中呈現數據來獲取數據。 但是我無法枚舉組件中可觀察對象返回的數據。 在將數據發送到模板之前,我想在組件級別對其進行處理。

到目前為止,我已經嘗試過了:

我的服務:

getCountries(): Observable<IUser> {
   return this.http.get<IUser>('https://jsonplaceholder.typicode.com/posts');
}

我在組件中的ngInit方法:

 ngOnInit() {
    this.countryService.getCountries().subscribe((users => {
       this.userJson = users;
    }));

    console.log(this.userJson); // Showing undefined

    //giving exception while calling length property
    for (var i = 0; i < this.userJson.length; i++) {
    }
}

不確定如何處理?

您需要在subscribe方法中編寫邏輯。 這是一個異步調用,您不知道何時完成。

this.countryService.getCountries().subscribe((users => {
   this.userJson = users;

   console.log(this.userJson);

   for (var i = 0; i < this.userJson.length; i++) {

   }
}));

您仍然可以在標記中使用userJson -Angular將檢測this.userJson的值this.userJson更新,並將自動更新UI。

您需要在訂閱中調用console.log使其起作用,為什么還要在內部調用? 因為它是異步請求;您可以通過調用以下函數來遍歷項目,

ngOnInit() {
  this.countryService.getCountries().subscribe((users => {
    this.userJson = users;
    console.log(this.userJson); 
    printMe(this.usersJson);
}));

printMe : void (){
  for (var i = 0; i < this.userJson.length; i++) {
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM