简体   繁体   English

http 等待另一个呼叫完成

[英]http wait for another call finish

scenario :场景

  • members and non-members have different contents in the same page, eg news, user info会员和非会员在同一页面有不同的内容,例如新闻,用户信息
  • "remember me" feature is available “记住我”功能可用
  • check the token in local storage with server to verify user when website is loaded加载网站时使用服务器检查本地存储中的令牌以验证用户
  • most of http request result will be different based on login status大多数 http 请求结果将根据登录状态而有所不同

problem :问题

  • how can I wait for user validation before all http request is triggered?如何在触发所有 http 请求之前等待用户验证?

http.service.ts sample code : 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);
    }
  }

sandbox sample is here沙盒示例在这里

You can try like this.你可以这样试试。 In app component在应用程序组件中

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

    // Then call your other things
  }

HttpService.ts HttpService.ts

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

This is the code sandbox link这是代码沙箱链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何等待服务HTTP调用完成组件 - How to wait for service HTTP call to finish in component 等待http请求完成,然后在角度6的另一个http请求中使用结果 - wait http request to finish, then use the result in another http request in angular 6 Angular 7 在触发下一个之前等待 http 网络调用完成 - Angular 7 Wait for http network call to finish before triggering next one 在使用从第一个 http 调用中检索到的参数运行下一个 http 调用之前,如何等待一个 http 调用完成? - How do I wait for one http call to finish before the next http call runs with an argument retrieved from the first http call? 量角器等待休息电话完成 - Protractor wait for rest call finish angular 用于循环进行 http 调用 - 等待上一个调用完成,然后再进行下一个 - angular for loop making http call - wait for previous call to finish before making next 等待http请求单元完成角度(服务) - wait http req unit finish angular (services) 等待 Http 请求完成使用 NestJS - Wait for Http Request to finish using NestJS 如何在 Angular 中等待 http 请求完成? - How to wait for a http request to finish in Angular? 我如何等待异步管道完成并在不订阅的情况下调用另一个函数 - How can I wait async pipe to finish and call another function after, without subscribing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM