簡體   English   中英

准備好后,使用可觀察到的角度值

[英]use values from observable in angular when they are ready

我從可觀察的獲取數據,然后對其進行處理。

我的實際問題是,當我在調用它后使用可觀察的數據時,它永遠不會到達。

但是當我console.log結果出現在subscribe()方法中的時候,數據就來了。

我以為Angular在獲取數據時會再次調用生命周期鈎子,但事實並非如此。

refreshData() {

  this.apiService.retrieveIndicatorHistory(this.indicatorName, this.currentPeriod).subscribe(res => {
    this.values$.push(res);
    console.log("values",res)
  });
}

ngOnInit() {
  this.refreshData();
  ... few steps after
  console.log("values are here", this.values$); // always empty
}

然后我也嘗試在Onchange顯示值,但數據從不打印

ngOnChanges() {
  console.log("values are here", this.values$);
  // manipulate data
}

准備好從可觀察值中獲得的值時,如何處理它們? 我是否應該將所有業務邏輯放入subscribe()

RxJS Observable以異步方式工作,在接收到數據后將發出一次數據。 因此輸入和輸出將是可觀察的。 為了讀取可觀察的數據,首先需要訂閱它。

refreshData() {

  this.apiService.retrieveIndicatorHistory(this.indicatorName, this.currentPeriod).subscribe(res => {
    this.values$.push(res);
    this.processData();
  });
}

ngOnInit() {
  this.refreshData();
}

processData(){
  console.log(this.values$); // you can access data here.
}

您不應該在訂閱中加入業務邏輯。 通常,所有業務邏輯都應放在pipe()中。 您可以使用異步管道在hTML中直接訂閱可觀察的內容。

因此在html中應該是:

 <ul *ngFor="let value of (values$ | async)">
  <li>{{value}}</li>
 </ul>

在component.ts內部:

values = []
values$ = this.apiService.retrieveIndicatorHistory(this.indicatorName, this.currentPeriod).pipe(
  map(res => {
    this.values.push(res);
    return this.values
  })
)

是的,這是一個異步調用,並且訂閱將在數據到達時及時知道,ngOnInit中的任何內容都將執行且不會等待。

否則你可以使用(async,await)組合

暫無
暫無

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

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