代码之家  ›  专栏  ›  技术社区  ›  D.B

从HttpModule迁移到HttpClientModule。角度5

  •  1
  • D.B  · 技术社区  · 8 年前

    我正在尝试从角度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 回复  |  直到 8 年前
        1
  •  1
  •   Sajeetharan    8 年前

    只需返回可观察的,

    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
    })
    
    推荐文章