有谁知道是否有机会从商店获取价值然后调用 Angular http 服务?请参见下面的示例。提前致谢。
我有一个异步方法的服务。在这种方法中,我调用了 angular http 服务,但在调用 angular http 服务之前,我想从存储中检索一些值(oauth 访问令牌)。问题是我将 oauth 令牌存储在商店中,并且必须将令牌添加到请求中。如果服务器响应 401 错误,我会刷新令牌并使用新令牌重复请求或请求。
@Injectable()
export class Interceptor {
public get(request: Request): Observable<any> {
return this.store.select((s) => s.session.accessToken)
// tried .switchMap, it wasn't working for multiple requests
// .flatMap also is not working
// commented below is working but I don't think that it is right solution
// return Observable.of(request)
// .withLatestFrom(this.store.select((s) => {
// return s.session.accessToken
// }))
// .flatMap(([config, accessToken]) => { ... })
.flatMap((accessToken) => {
request.headers.set("Authorization", `Bearer ${accessToken}`);
return this.http.request(request);
})
.map((response) => {
return response.json();
})
.catch((response) => {
return this.handleError(response, request);
});
}
// handle errors
private handleError(response: Response, request: Request): Observable<Response> {
// handle outdated api tokens
if (response.status === HttpStatusesEnum.Unauthorized) {
const deferredRequest = new DeferredRequestModel({ request });
// appends HTTP request configuration object with deferred response
// attached to buffer
this.buffer(deferredRequest );
return deferredRequest.observable;
}
// handle server error
if (response.status === HttpStatusesEnum.InternalServerError) {
...
}
...
return Observable.throw(response);
}
}
export class DeferredRequestModel {
public observable: AsyncSubject<Response>;
public request: Request;
constructor(obj?: Partial<DeferredRequestModel>) {
this.observable = new AsyncSubject<Response>();
this.request = obj && obj.request || null;
}
public reject(error?: any): void {
this.end({ isValue: false, value: error });
}
public resolve(value?: any): void {
this.end({ isValue: true, value });
}
private end(result: any): void {
if (this.observable.isStopped) {
console.warn("Deferred already resloved/rejected.");
return;
}
if (result.isValue) {
this.observable.next(result.value);
this.observable.complete();
} else {
this.observable.error(result.error);
}
}
}
然后当我调用一些服务时,它会通过拦截器发送请求。
export class SomeEffect {
constructor(private someService: SomeService) {}
@Effect()
public someMethod(): Observable<Action> {
return this.actions$.ofType(SOME_ACTION_GET)
.map((action: SomeActions.Get) => action.payload)
.switchMap((someObj) => {
// someMethod call interceptor inside someService, it won't call angular
// http service directly
return this.someService.someMethod(someObj);
})
.map((someResult) => {
return new SomeActions.GetSuccess(someResult);
});
}
}
我尝试在拦截器中使用 switchMap,但如果拦截器被多次调用,它将不起作用。