infodev
infodev

Reputation: 5235

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() ?

Upvotes: 0

Views: 837

Answers (3)

Oleg
Oleg

Reputation: 401

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

Upvotes: 1

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9764

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

Upvotes: 2

HGrover
HGrover

Reputation: 225

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

Upvotes: 0

Related Questions