json - Angular 6 HTTPClient : Request fired once, 收到 2 个响应

标签 json node.js angular http

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

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} 吗?

最佳答案

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

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

这里是引用。 https://angular.io/api/common/http/HttpClient#request

关于json - Angular 6 HTTPClient : Request fired once, 收到 2 个响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50105311/

相关文章:

node.js - 如何在 Nestjs 中创建 mongodb 连接提供程序

angular - Angular 2.0 能理解 Polymers Shadow DOM 吗?

javascript - Angular Http 订阅不工作

浏览器中的 Typescript 转译与预编译 js 文件

php - while 循环将所有行连接为一行?

arrays - 如何解码 json 并填充到 golang 中的结构

node.js - 使用 nodeJS 关闭端口

java - 导入由 JSON 序列化的 json 失败

json - 在 Play2 scala 应用程序中执行 json 读取和写入时如何排除值

node.js - Feathersjs 与 Express JS