简体   繁体   English

准备好后,使用可观察到的角度值

[英]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. 但是当我console.log结果出现在subscribe()方法中的时候,数据就来了。

I thought that Angular will call again lifecyclehooks when I get data but it's not the case. 我以为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
}

Then I tried to show values inside Onchange also but data never prints 然后我也尝试在Onchange显示值,但数据从不打印

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() ? 我是否应该将所有业务逻辑放入subscribe()

RxJS Observable works in async manner, it will emit the data once after it is received. RxJS Observable以异步方式工作,在接收到数据后将发出一次数据。 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(). 通常,所有业务逻辑都应放在pipe()中。 And you can subscribe to observable directly in hTML using async pipe. 您可以使用异步管道在hTML中直接订阅可观察的内容。

So in html should be: 因此在html中应该是:

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

and inside component.ts: 在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. 是的,这是一个异步调用,并且订阅将在数据到达时及时知道,ngOnInit中的任何内容都将执行且不会等待。

Else you can use (async, await ) combination 否则你可以使用(async,await)组合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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