[Angular 2] Async Http

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Angular 2] Async Http相关的知识,希望对你有一定的参考价值。

Async Pipe:

The Asynce pipe receive a Promise or Observable as  input and subscribes to the input, evetually emitting the value(s) changes arrive.

 

In the demo, the logic is fom the list component, we ask service to get Heros by calling Start War API, on the service side, we only return array of heros with observalbe type:

    getHeros(){
        return this._http.get(http://swapi.co/api/people)
            .map( (res: Response) => <Hero[]>res.json().results)
            .catch(this.handleError);
    }

 ...

export class Hero{
    constructor(public name: string){}
}

 

Here <Hero[]>, we use Typescript to convert the raw json data to Hero[]. The same as you new Hero().

 

For the list, we assign the return value from service to this.heros , so it is a list of Hero with Observable type, then we apply async pipe to the html.

    heros: Observable<Hero[]>;

    getHeros(){
        this.heros = this.heroService.getHeros();
    }
        <ul>
            <li *ngFor="#hero of heros | async">
                {{hero.name}}
            </li>
        </ul>

 

 

 

以上是关于[Angular 2] Async Http的主要内容,如果未能解决你的问题,请参考以下文章

[Angular 2] Handle Reactive Async opreations in Service

Angular2 - 将 ASYNC 数据传递给子组件

从Angular HttpClient调用Async方法azure AI计算机视觉获取响应标头

Angular 2 - 当(observableData | async)尚未解决时显示加载信息

Angular 8 - 如何使用 Promises 和 Async/Await [重复]

无法在 Angular2 中进行 http 服务调用?