【问题标题】:Angular How to Wait for Response using HttpClientAngular 如何使用 HttpClient 等待响应
【发布时间】:2020-06-26 19:01:17
【问题描述】:

我在我的 Angular 应用程序上使用了一个 restful api。

forgotPassword(mail: string) {
    const apiURL = 'https://myapiendpoint';
    const connect = this.httpClient.post(apiURL, { email: mail },
        { headers: {
             'Content-type': 'application/json',
             responseType: 'text'
            }
    });
        return connect.toPromise();
    }

API 被调用没有问题,但我无法从服务器获得响应。 创建 API 的人说他可以看到:

在收到响应之前关闭消息端口

有什么建议吗?

谢谢

【问题讨论】:

  • 您订阅此请求的代码部分在哪里?
  • 像这样简单订阅 POST 请求 Observable.httpClient.post(apiURL, { email: mail }).subscribe();

标签: angular httpclient


【解决方案1】:

请不要对 http 请求使用 Promises,这不是 reactjs。

改用 Observables

forgotPassword(email: string): Observable<any> {
    const httpOptions = {
       headers: new HttpHeaders({
        'Content-Type': 'application/json'
        })
    };

    const queryUrl: string = `'https://myapiendpoint`;

    return this.http
      .post<any>(queryUrl, JSON.stringify(email), httpOptions)
      .pipe(
        map((response: any) => {
          return response;
        })
      );
  }

然后只需从您的组件订阅:

service.forgotPassword(email).subscribe(result => {
 // do something
});

【讨论】:

  • 嘿@AlleXyS 我按照你的描述试过了,但我仍然收到同样的错误:/这可能是 API 上的错误吗?
  • 请分享你的httpinterceptor
猜你喜欢
  • 1970-01-01
  • 2018-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2020-01-06
相关资源
最近更新 更多