【问题标题】:Angular 6 HTTPClient: Request fired once, receives 2 responsesAngular 6 HTTPClient:请求触发一次,收到2个响应
【发布时间】:2023-03-16 19:15:02
【问题描述】:

我已经将一个旧项目(Angular 2)重构为 Angular 6。除了 api 调用存在问题外,一切正常。 在登录组件上,当我提交表单时,会触发一个带有数据的 POST 请求,并且拦截器会添加某些标头(目前只有内容类型)。 提交表单代码:

this.authService.signIn(this.account)
        .subscribe( res => {
          console.log('RES -> ', res);
          this.router.navigate([this.returnUrl]);
        },
          err => console.log(err));

AuthService 方法:

 signIn(account: Account) {
    const req = new HttpRequest(HttpMethods.Post, AuthService.signInUrl,{account: account});
    return this.makeRequest(req);
   }

private makeRequest(req: HttpRequest<any>): Observable<any> {
    this.progressBarService.availableProgress(true);
    return this.http.request(req)
        .finally( () => this.progressBarService.availableProgress(false));
  }

我添加的console.log 由于某种原因被触发了两次:第一次是{type: 0},第二次返回我需要的数据。 我已经从拦截器中删除了所有内容,只留下了next.handle(req),它也是如此。 知道为什么我收到 2 个回复,第一个只是 {type: 0}

【问题讨论】:

  • 使用简单的 http.post 请求等修复此问题。

标签: json node.js angular http


【解决方案1】:

那是因为你使用了this.http.request()。我猜第一个响应实际上是对 OPTIONS 请求的响应。

如果您仍然坚持使用this.http.request(),例如如果您使用它来上传文件,您可能需要使用rxJs takeLast(1) 来获得您需要的响应。

这是参考。 https://angular.io/api/common/http/HttpClient#request

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 2022-11-20
    • 2021-03-02
    • 1970-01-01
    相关资源
    最近更新 更多