繁体   English   中英

Angular 如何使用 HttpClient 等待响应

[英]Angular How to Wait for Response using HttpClient

我在我的 angular 应用程序上使用了一个安静的 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 的人说他可以看到:

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

有小费吗?

谢谢

请不要对 http 请求使用 Promise,这不是 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
});

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM