简体   繁体   中英

use values from observable in angular when they are ready

I'm getting data from observable then manipulating it.

My actual problem is that when I would use data from observable after calling it never get arrived.

But when I console.log result inside subscribe() method at a moment data comes.

I thought that Angular will call again lifecyclehooks when I get data but it's not the case.

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
}

Then I tried to show values inside Onchange also but data never prints

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

How can I manipulate values that I get from observable when they get ready ? Should I put all my business logic inside subscribe() ?

RxJS Observable works in async manner, it will emit the data once after it is received. So input and output will be an observable. In order to read the observable data, first you need to subscribe to it.

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.
}

You should not put business logic in subscribe. In general, all business logic should be placed in pipe(). And you can subscribe to observable directly in hTML using async pipe.

So in html should be:

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

and inside component.ts:

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

Yes, It's an async call and the subscribe will exactly know in time when data arrives, anything in ngOnInit will execute and won't wait for it.

Else you can use (async, await ) combination

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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