如果有人能对此有所说明,我将不胜感激。我已经去了好几天了。
这是我的身份验证服务中存在的两个功能。登录函数先检索有效的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”导入了地图
答案 0 :(得分:2)
您可以这样做:
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))
);
我认为此解决方案更加简洁。