从HttpModule迁移到HttpClientModule。 Angular 5

时间:2017-11-26 03:44:55

标签: angular angular-httpclient

我正在尝试从角度HttpModule迁移到角度HttpClientModule。

我目前使用HttpModule的代码如下:

constructor(private _http: Http) { }

 token: IToken;
 errorMesage: string;

 private _candidateLoginUrl = 'http://myapi/v1/auth/login';

 login(userName: string, password: string): Observable<IToken> {

  let body = JSON.stringify({ username: userName, password: password });
  let headers = new Headers();
  headers.append("Content-Type", 'application/json');
  let options = new RequestOptions({ headers: headers });

  return this._http.post(this._candidateLoginUrl, body, options)
    .map((response: Response) => {

      this.token = <any>response.json().data;

      if (this.token && this.token.token) {            
        localStorage.setItem('currentUser', JSON.stringify(this.token));
      }

      return this.token;
    })
    .catch(this.handleError);
  } 

  private handleError(error: Response) {
    return Observable.throw('You are not authorized to get this resource');
  }

为了保持相同的逻辑,我已经完成了以下工作:

constructor(private _http: HttpClient) { }

token: IToken;
errorMesage: string;

private _candidateLoginUrl = 'http://myapi/v1/auth/login';

login(userName: string, password: string): Observable<IToken> {

  let body = JSON.stringify({ username: userName, password: password });  
  const headers = new HttpHeaders().set("Content-Type", 'application/json');

  this._http.post(this._candidateLoginUrl, body, { headers })    

  .map((response: Response) => {

            this.token = <any>response;

            if (this.token && this.token.token) {               
              localStorage.setItem('currentUser', JSON.stringify(this.token));
            }

            return this.token;
          })

  .catch(this.handleError);
}

private handleError(error: Response) {
  return Observable.throw('You are not authorized to get this resource');
}

但是,我从登录函数收到一个错误:“一个声明类型为'void'而不是任何必须返回值的函数”。将代码迁移到HttpClientModule的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

只需返回observable,

return this._http.post(this._candidateLoginUrl, body, { headers }).map((response: Response) => {
     //consider returning the response and assign the token wherever you are consuming this method
})