【问题标题】:Angular v6 pipe(map()) issueAngular v6 管道(map())问题
【发布时间】:2018-10-03 07:30:09
【问题描述】:

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

这是我的身份验证服务中的两个功能。检索有效 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;

}

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

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

我已经从 'rxjs/operators' 导入了地图

【问题讨论】:

  • 试试pipe(map(this._mapTokenResponse);
  • 哪个 IDE 显示这样的错误?你能用stackblitz.com复制同样的内容吗?
  • 这是 chrome v69 和 Firefox。
  • 缺少一个括号?这就是我尝试过的无济于事。但是,将其作为第二个参数传递并没有错。这只是说明项目必须对此做什么。请参阅此答案 stackoverflow.com/a/46389132/4337399
  • 为什么不使用 pipe(map(token=>{ return this._mapTokenResponse(token)})) 而你的函数作为参数接收一个令牌?

标签: angular rxjs rxjs-lettable-operators


【解决方案1】:

你可以这样做:

  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))
  );

在我看来,这个解决方案要干净得多。

【讨论】:

    猜你喜欢
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2012-04-15
    • 1970-01-01
    相关资源
    最近更新 更多