使用Observables“返回”异步数据

时间:2018-01-30 02:35:32

标签: angular observable rxjs5

说我的HTML中有这个:

  <div>
    <mat-label>Matched events count: {{(getMatchedEventsCount() | async)?}}</mat-label>
  </div>
  <div>
    <mat-label>Total events count: {{(getTotalEventsCount() | async)?}}</mat-label>
  </div>

我的问题是,从这些辅助方法返回什么(就Observable而言)?

  getMatchedEventsCount(){
    return Observable.of(3);
  }

  getTotalEventsCount(){
    return Observable.of(5);
  }

但我的问题是 - 我们怎么能做一些实际上异步的事情?

目前,我收到此HTML解析错误:

  

未捕获错误:模板解析错误:解析器错误:意外结束   表达式:匹配事件计数:{{(getMatchedEventsCount()|   async)?}}在表达式的末尾[匹配事件计数:   {{(getMatchedEventsCount()| async)?}}] in   ng:///AppModule/EventsListComponent.html@40:21(“                                   [错误 - &gt;]匹配事件计数:{{(getMatchedEventsCount()| async)?}}                      “):ng:///AppModule/EventsListComponent.html@40:21解析器错误:条件表达式(getMatchedEventsCount()| async)?   需要表达式末尾的所有3个表达式[匹配   事件计数:{{(getMatchedEventsCount()| async)?}}] in   ng:///AppModule/EventsListComponent.html@40:21(“                                   [错误 - &gt;]匹配事件计数:{{(getMatchedEventsCount()| async)?}}                      “):ng:///AppModule/EventsListComponent.html@40:21

1 个答案:

答案 0 :(得分:1)

我注意到您已经对注释帖子中的?进行了问题排查。 ?(称为"save navigation operator")不起作用的原因是它在属性路径中防范nullundefined值,意味着您需要在使用?后尝试访问属性。现在,您正在尝试追溯使用它来查看对象是null还是undefined,但它只能向前看到对象,而不是向后,它需要一个属性来查找。

你是正确的,你应该从方法中返回Observable并将其提供给async管道。以下是关于async管道的一些文档:https://angular.io/api/common/AsyncPipe

关于如何使用Subscription加载数据而不是Observable的评论主题中的问题...

您可以使用subscribe方法执行此操作,并将数据分配给组件上的属性,如下所示:

matchedEventsSub: Subscription;
matchedEventsCount: number;

getMatchedEventsCount() {
  this.matchedEventsSub = Observable.of(3).subscribe(value => {
    this.matchedEventsCount = value;
  });
}

请注意,subscribe Observable会返回Subscription。然后,您必须记住unsubscribe生命周期钩子中的订阅OnDestroy以防止内存泄漏:

ngOnDestroy() {
  if (this.matchedEventsSub) { this.matchedEventsSub.unsubscribe(); }
}

可以想象,如果在一个组件中有2个,3个,10个订阅,则会变得很麻烦。这就是Angular团队创建async管道的原因。

最后,

  

我们怎么能做一些实际上异步的事?

实际上非常简单。我们假设你有EventsService注入你的组件:

constructor(private eventsService: EventService) {}

该服务可以封装Http请求或其他内容 - Angular的HttpClient模块使用Observable来表示异步数据。您可以使用EventsService来获取这样的异步事件流:

matchedEventsCount$: Observable<number>;

getMatchedEventsCount(): Observable<number> {
  const allEvents$ = this.eventsService.getEvents();
  return allEvents$.map(events => events.length);
}

调用OnInit生命周期挂钩中的方法来填充数据:

ngOnInit() {
  this.getMatchedEventsCount();
}

然后将其显示在您的模板中:

<h1>Events: {{ matchedEventsCount$ | async }}</h1>
相关问题