繁体   English   中英

如何通过HttpClient简单地从POST请求中读取响应?

[英]How to simply read response from POST request via HttpClient?

在我的Service类中,我有一个变量一个被调用的token ,我想在调用一个函数时为它赋值。 假设有一个名为login的方法,它只应该从包含的post请求中返回响应:

login(email: string, password: string): Observable<Response> {
    return this.httpClient.post(url, {email: email, password: password})
          .pipe(
            catchError(error => of(error))
          );
} 

该功能可能看起来像那样。 在其中,我现在尝试将Response中的值this.token

我怎么能解决这个问题?

login(email: string, password: string): Observable<Response> {
    return this.httpClient.post(url, {email: email, password: password}).subscribe(data => {
        this.token = data.token;
    }, err => {
        console.log(err);
        return false;
    )
} 

您可以使用以下代码获取响应并设置this.token

/* 
Your user model can be like this: 
interface User {
  token: string;
}
*/
this.httpClient.post(url, {email: email, password: password}).pipe(
      tap(async (userInfo: User) => {
        // login successful if there's a jwt token in the response
        if (userInfo) {                    
          this.token = userInfo.token;
        }
        return userInfo;
      })
    );

您还可以指定期望作为响应的模型类型,如下所示:

this.httpClient.post<User>(url, {email: email, password: password})

在这里您可以在代码中使用它:

login(email: string, password: string): Observable<Response> {
    return this.httpClient.post(url, {email: email, password: password}).pipe(
      tap(async (response: Response) => {
        // login successful if there's a jwt token in the response
        if (response) {                    
          this.token = response.token;
        }
        return response;
      })
    );
} 

在我看来,最简单的方法是使用RXJS,让一切变得更简单。

httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

private loginService(url, data) {
        try {
          return this._http.post(
            Url,
            data,
            this.httpOptions
          );
        } catch (e) {
          console.log(e);
        }
      }

httpClient已经返回一个observable,因此无需声明它。 然后你只需订阅它:

    this.loginService(url, {email: email, password: password}).subscribe(
          (data) => {
            console.log('Login info');
          },
          (error) => console.log(error),
          () => {
            console.log('Complete);
          },
        );

暂无
暂无

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

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