使用async/await而不是subscribe传递变量



我试图将async/await用于双API调用,但第二个async函数中的变量不起作用或Angular不呈现。

const pokemon = this.httpClient
.get(`https://pokeapi.co/api/v2/pokemon/${pokemon_name}`)
.subscribe(pokemon => {
this.image = pokemon["sprites"]["front_default"];
});

我认为这是针对Angular中组件的生命周期,但我不知道如何解决

https://stackblitz.com/edit/angular-http-async-await-q4m6d7?file=src%2Fapp%2Fapp.component.ts

我没有看到将可观察到的转化为承诺的任何显式用途。特别是当涉及到链式请求时,最好使用可观察的值,并使用RxJS运算符,这些运算符是为在这些情况下提供帮助而设计的。

在您的情况下,您需要多次更改。

  1. 内部请求取决于外部请求的响应。您可以使用RxJSswitchMap运算符来映射此处的可观测值。

  2. 外部请求返回一组URL,每个URL都需要单独触发才能获得图像。在这里,您可以使用RxJSforkJoin函数来并行触发多个请求。

  3. 然后可以将结果映射到一个URL数组,该数组可以使用模板中的Angularasync管道进行订阅。

  4. 由于它是一个图像数组,您可以使用*ngFor指令循环遍历它们。

控制器

import { Component, OnInit } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable, forkJoin } from "rxjs";
import { switchMap, map } from "rxjs/operators";
@Component({ ... })
export class AppComponent implements OnInit {
images: Observable<any>;
constructor(private httpClient: HttpClient) {}
ngOnInit() {
this.doSometing();
}
doSometing() {
this.images = this.httpClient
.get("https://pokeapi.co/api/v2/pokemon?limit=151")
.pipe(
switchMap((pokemons: any) =>
forkJoin(
pokemons.results.map((result: any) =>
this.httpClient
.get(result.url)
.pipe(map((pokemon: any) => pokemon.sprites.front_default))
)
)
)
);
}
}

模板

<ng-container *ngIf="(images | async) as urls">
<h1>Images</h1>
<img *ngFor="let url of urls" [src]="url"/>
</ng-container>

我修改了你的Stacklitz


注意:toPromise()将在RxJS 7中弃用,并将在Rx JS 8中消失。

最新更新