【问题标题】:How to call backend apis after finishing the first api call in angular 13?在 Angular 13 中完成第一个 api 调用后如何调用后端 api?
【发布时间】:2023-02-21 14:48:13
【问题描述】:

我正在处理角度 13。我在一个组件中有 4 个 api 调用,但只有一个 api 调用足以呈现视图。其余 3 个 api 调用仅用于内部编码目的。 我想在完成第一个 api 调用后调用其余 3 个 api 调用怎么办? 我已经尝试过角度的生命周期挂钩但是并行 api 调用正在进行

【问题讨论】:

    标签: angular


    【解决方案1】:

    我们说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
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-22
      • 2016-04-24
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 2019-10-31
      • 1970-01-01
      • 2020-10-12
      相关资源
      最近更新 更多