在文档(https://www.apollographql.com/docs/angular/recipes/authentication/)中有一个例子。但是,如果您有一个 angular-apollo watch().valueChanges 或 fetch() 作为返回的 Observable,这不起作用...
我的代码是:
const auth = setContext(async (_, {headers}) => {
let token = authService.getAccessToken();
if (!authService.hasValidAccessToken()) {
if (authService.hasRefreshToken()) {
await this.authService.refreshToken().pipe(first()).toPromise(); //Does not work...
token = authService.getAccessToken();
}
}
// Return the headers as usual
return {
headers: {
Authorization: `Bearer ${token}`,
},
};
});
authService.refreshToken() 方法返回这个:
refreshToken(): Observable<any> {
this.removeAccessToken();
if (this.hasRefreshToken()) {
return this.refreshGQL.fetch({
refreshToken: this.getRefreshToken()
}).pipe(
tap(next => {
this.storeTokens(next.data.refresh);
}
)
);
}
问题是,不能调用订阅,这将启动 Observable。你有解决方案吗?