Angular v6 管道(地图())问题

Angular v6 pipe(map()) issue

如果有人能对此有所说明,我将不胜感激。我已经做了好几天了。

这是我的身份验证服务中的两个函数。检索有效 jwt 的登录函数,然后是获取刷新的 jwt 的刷新函数。

登录

  login(username: string, password: string): Observable<any> {
    const headers = new HttpHeaders().set('Authorization', `Basic ${environment.WSO2_AUTH_BASIC}`);
    const params = new HttpParams({
    fromObject: {
     grant_type: 'password',
     scope: 'openid',
     username: username,
     password: password
   }
 });

  return this.http.request<Token>('POST', environment.API_HOST + '/token', {
    headers: headers,
    body: params
  }).pipe(map(this._mapTokenResponse));
}

刷新

  private _refreshToken() {
const headers = new HttpHeaders().set('Authorization', `Basic ${environment.WSO2_AUTH_BASIC}`);
this.token = this.getToken();
const params = new HttpParams({
  fromObject: {
    grant_type: 'refresh_token',
    scope: 'openid',
    refresh_token: this.token.refresh_token
  }
});
return this.http.request<Token>('POST', environment.API_HOST + '/token', {
  headers: headers,
  params: params
}).pipe(map(this._mapTokenResponse, this));
}

我创建了一个单独的箭头函数来处理两者的映射。

private _mapTokenResponse = (token: Token) => {
// login successful if there's a jwt token in the response
if (token && token.access_token) {
  // store user details and jwt token in local storage to keep user logged in between page refreshes
  token.id_token_data = this.jwtHelper.decodeToken(token.id_token);
  this._setSession(token);
}
return token;

}

我想要这个,这样我就不会重复代码。登录功能完美运行,但刷新令牌 returns 此错误:

ERROR Error: "Uncaught (in promise): TypeError: argument is not a function. Are you looking for `mapTo()`?

我已经从 'rxjs/operators'

导入了地图

你可以这样做:

  return this.http.request<Token>('POST', environment.API_HOST + '/token', {
    headers: headers,
    body: params
  }).pipe(
    map(this._mapTokenResponse.bind(this))
  );

我们使用.bind(this)来设置函数调用的范围("this")。否则,每次在回调函数中调用 this. 时都会出错。

或者:

  return this.http.request<Token>('POST', environment.API_HOST + '/token', {
    headers: headers,
    body: params
  }).pipe(
    map((token: Token) => this._mapTokenResponse(token))
  );

我认为此解决方案更简洁。