首页 > 解决方案 > http 等待另一个呼叫完成

问题描述

场景

问题

http.service.ts 示例代码

  private isReady = false;

  constructor(private httpClient: HttpClient) {
    this.init();
  }

  // pass local data to check user login status
  // check the token, expired date etc.
  public init() {
    // this.httpClient.post to verify user status
    // this.isReady = true;
  }

  // http get request used in other components
  public get(url) {
    if (this.isReady) {
      return this.httpClient.get<any>(this.apiRoot + url);
    } else {
      // how to wait for init() is done before return in here?
      return this.httpClient.get<any>(this.apiRoot + url);
    }
  }

沙盒示例在这里

标签: angular

解决方案


你可以这样试试。在应用程序组件中

async ngOnInit() {
    await this.http.init(); // wait until init complete

    // Then call your other things
  }

HttpService.ts

public async init(): Promise<void> {
    await this.httpClient
      .get<any>(this.apiRoot + "assets/user.json")
      .toPromise()
      .then(s => {
        console.log("init completed");
      });
  }

这是代码沙箱链接


推荐阅读