且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Angular里使用rxjs的异步API - Observable

更新时间:2022-09-09 16:39:28

Angular的service类里,导入Observable和of:在Angular里使用rxjs的异步API - Observable

of(HEROES) returns an Observable that emits a single value, the array of mock heroes.


下面是消费端如何调用这个返回Observable的TypeScript代码:

 getHeroes(): void {
    this.heroService.getHeroes()
        .subscribe(heroes => this.heroes = heroes);
  }

注意将其同之前的同步API相比较:在Angular里使用rxjs的异步API - Observable

The new version waits for the Observable to emit the array of heroes—which could happen now or several minutes from now. The subscribe() method passes the emitted array to the callback, which sets the component’s heroes property.


第32行,调用OBservable API的subscribe方法,方法接收一个回调函数,设置Component的heroes属性为Observable里包裹的数组。


在调试器里能观察到这个回调函数是如何被observable框架异步调用的:

在Angular里使用rxjs的异步API - Observable