【发布时间】:2023-02-21 14:48:13
【问题描述】:
我正在处理角度 13。我在一个组件中有 4 个 api 调用,但只有一个 api 调用足以呈现视图。其余 3 个 api 调用仅用于内部编码目的。 我想在完成第一个 api 调用后调用其余 3 个 api 调用怎么办? 我已经尝试过角度的生命周期挂钩但是并行 api 调用正在进行
【问题讨论】:
标签: angular
我正在处理角度 13。我在一个组件中有 4 个 api 调用,但只有一个 api 调用足以呈现视图。其余 3 个 api 调用仅用于内部编码目的。 我想在完成第一个 api 调用后调用其余 3 个 api 调用怎么办? 我已经尝试过角度的生命周期挂钩但是并行 api 调用正在进行
【问题讨论】:
标签: angular
我们说ApiOne是重要的。然后你可以简单地这样做:
代码
constructor(private myService: MyService) {
this.loading = true;
}
ngOnInit() {
this.myService.apiOne().subscribe(data => {
this.myService.apiTwo().subscribe(data => { console.log("Service Done..."});
this.myService.apiThree().subscribe(data => { console.log("Service Done..."});
this.myService.apiFour().subscribe(data => { console.log("Service Done..."});
this.loading = false;
})
}
HTML
<div *ngIf="!loading">
<!-- Your content -->
</div>
<loading-spinner *ngIf="loading"></loading-spinner>
您也可以为 httpClient 使用 toPromise 而不是 subscribe。
顺便说一句:toPromise 已弃用,您可以使用更新的firstValueFrom。
代码
async myLoader() {
const result = await firstValueFrom(this.myService.apiOne());
this.loading = false;
// Do other stuff
}
【讨论】: