In the Angular service class, import Observable and of:

of(HEROES) returns an Observable<Hero[]> that emits a single value, the array of mock heroes.

Here’s how the consumer calls the TypeScript code that returns Observable<Hero[]> :

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

Note how this compares to the previous synchronization API:

The new version of 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.

Line 32 calls the Subscribe method of the OBservable API. The method receives a callback that sets the Heroes property of the Component to the array wrapped in the OBservable.

In the debugger, you can see how this callback is asynchronously called by the Observable framework:



For more of Jerry’s original articles, please follow the public account “Wang Zixi “: