2017-08-21 111 views
0

我有一種服務,我打電話給我的ngOnInit方法。它返回並填充我的數組。然後我使用第一個數組的結果調用另一個服務方法,該方法依次填充第二個數組。延遲的服務呼叫不顯示在視圖上

我的問題是,在渲染我的第二個數組時,我認爲它仍然是空的,所以它永遠不會呈現在屏幕上。

下面是一個簡單的例子:

changedBookings: Booking[] = []; 
 
currentBookings: Booking[] = []; 
 

 
constructor(private bookingService: BookingService) { } 
 

 
    ngOnInit() { 
 

 
    //Get all changes then filter 
 
    this.bookingService.getAllHistory() 
 
     .subscribe(
 
      data => { 
 
       this.changedBookings = (data as any).results 
 
      }, 
 
      err => { 
 
       console.log(err); 
 
      }, 
 
      () => { 
 
       this.getCurrentBookings(); 
 
      }) 
 
    } 
 

 
    getCurrentBookings() { 
 
     for(let i of this.changedBookings) { 
 
      this.bookingService.getRoomBooking(i.date,i.level,i.room) 
 
       .subscribe(
 
        data => this.currentBookings.push((data as any).results), 
 
        err => console.log(err), 
 
       () => { 
 
        //shows this array being filled 
 
        console.log(this.currentBookings); 
 
        } 
 
      ) 
 
     } 
 
    }
<div class="row"> 
 

 
    <div *ngFor="let booking of changedBookings"> 
 
    {{booking.date}} 
 
    </div> 
 

 
    <!--This one never shows--> 
 
    <div *ngFor="let booking of currentBookings"> 
 
    {{booking.date}} 
 
    </div> 
 
    
 
</div>

我怎麼能寫這樣的代碼,所以我可以在我的HTML代碼中使用兩個數組。

+0

更新並修復。 – Sisky

回答

0

最後簡單修復。但其他人可能會陷入困境。

getCurrentBookings() { 
    for(let i of this.changedBookings) { 
     this.bookingService.getRoomBooking(i.date,i.level,i.room) 
      .subscribe(
       data => this.currentBookings.push((data as any).results), 
       err => console.log(err), 
      () => { 
       //shows this array being filled 
       console.log(this.currentBookings); 
       } 
     ) 
    } 

}

,因爲這是通過它的循環,其實是推對象的數組,在每個循環,所以你最終的東西,像這樣:

[ [{}],[{}] ] 

所以很明顯

<div *ngFor="let booking of currentBookings"> 
    {{booking.date}} 
</div> 

將是未定義的。輕鬆修復而無需更改任何其他代碼,如下所示:

<div *ngFor="let booking of currentBookings"> 
    {{booking[0].date}} 
</div>