【发布时间】:2017-09-04 04:12:14
【问题描述】:
在下面的代码中,我发布了两个代码在控制台中返回的示例。对于拦截器,我应该返回一个可观察的。我已经使用 switchmap 将本地存储承诺转换为可观察的。我仍然使用这种方法返回 null。我的 observable 被包裹在函数周围,所以我应该得到一个不是 null 的值。谢谢!
Interceptor.js
import { fromPromise } from 'rxjs/observable/fromPromise';
accessToken: string;
emptyToken: any;
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
//example
this.storage.get('token').then((val) => {
this.accessToken = val
return console.log(this.accessToken, ' this is returning null value for token')
})
//trying to return actual header
return fromPromise(this.storage.get('token')).switchMap(access => {
this.accessToken = access
console.log(this.accessToken, ' this is returning null value for token')
const authReq = req.clone({
setHeaders: {
Authorization: this.accessToken
}
});
return next.handle(authReq)
})
}
}
我已经添加了下面的更新代码,请忽略上面的代码,仍然得到相同的结果。正如下面的答案之一,他们的所有假设都是正确的。归结为将令牌放入可观察的登录中。问题不在于拦截器,该代码工作正常。我需要以某种方式获取我的异步值而不返回 null。 this.storage.ready() 方法也给了我同样的结果。 身份验证服务在我的拦截器之后被调用,因此我还没有生成任何令牌。我将如何首先调用我的身份验证服务?
login(userName: string, password: string, route: string = null): any {
this.storage.set('tokens', 'able to retrieve this token value inside interceptor');
this.logout(false);
this.doLogin(userName, password)
.subscribe(response => {
let token:string = JSON.stringify(response.access_token);
this.storage.set('token', token)
}
}
interceptor.ts
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return Observable.fromPromise(
this.getRequestOptionArgs(options)
).mergeMap((options) => {
return super.get(url, options)
})
}
private getRequestOptionArgs(options?: RequestOptionsArgs) {
return this.storage.get('token').then((token) => {
console.log(token, 'token for the get')
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
if (token !== null) {
options.headers.append('Authorization', 'Bearer ' + token);
}
options.headers.append('Content-Type', 'application/json');
return options;
});
}
【问题讨论】:
-
尝试在
.switchMap(...)之前添加.filter(access => typeof access === string)。 -
我仍然得到相同的结果
-
对不起 string 需要用引号引起来:
typeof access === 'string' -
好消息是我不再收到那个空错误了。坏消息是我根本无法恢复访问权限,所以它只是停滞不前。
-
因为 promise 只会发出一个可观察的 once,在您的情况下显然是
null。你确定你保存了令牌吗?