使用Angular 4.3.1和HttpClient,我需要通过异步服务将请求和响应修改为httpClient的HttpInterceptor,
修改请求的示例:
export class UseAsyncServiceInterceptor implements HttpInterceptor {
constructor( private asyncService: AsyncService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// input request of applyLogic, output is async elaboration on request
this.asyncService.applyLogic(req).subscribe((modifiedReq) => {
const newReq = req.clone(modifiedReq);
return next.handle(newReq);
});
/* HERE, I have to return the Observable with next.handle but obviously
** I have a problem because I have to return
** newReq and here is not available. */
}
}
响应的问题不同,但我需要再次使用apply来更新响应。在这种情况下,角度指南建议如下:
return next.handle(req).do(event => {
if (event instanceof HttpResponse) {
// your async elaboration
}
}
但是“do()运算符 - 它会在不影响流的值的情况下为Observable添加副作用”。
解决方案:关于请求的解决方案由bsorrentino显示(进入接受的答案),关于响应的解决方案如下:
return next.handle(newReq).mergeMap((value: any) => {
return new Observable((observer) => {
if (value instanceof HttpResponse) {
// do async logic
this.asyncService.applyLogic(req).subscribe((modifiedRes) => {
const newRes = req.clone(modifiedRes);
observer.next(newRes);
});
}
});
});
因此,如何将异步服务的请求和响应修改为httpClient拦截器?
解决方案:利用rxjs
我认为有关反应流的问题。方法拦截期望返回一个Observable,你必须使用next.handle返回的Observable来展平你的异步结果
试试这个
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.asyncService.applyLogic(req).flatMap((modifiedReq)=> {
const newReq = req.clone(modifiedReq);
return next.handle(newReq);
});
}
您也可以使用switchMap而不是flatMap
上面的答案似乎很好。我有相同的要求,但由于不同依赖关系和运营商的更新而面临问题。花了我一些时间,但我找到了一个解决这个问题的工作方案。
如果您使用的是Angular 7和RxJs版本6+以及Async Interceptor请求的要求,那么您可以使用此代码,该代码适用于最新版本的NgRx存储和相关依赖项:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let combRef = combineLatest(this.store.select(App.getAppName));
return combRef.pipe( take(1), switchMap((result) => {
// Perform any updates in the request here
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log('event--->>>', event);
}
return event;
}),
catchError((error: HttpErrorResponse) => {
let data = {};
data = {
reason: error && error.error.reason ? error.error.reason : '',
status: error.status
};
return throwError(error);
}));
}));
好的我正在更新我的答案,您无法在异步服务中更新请求或响应,您必须同步更新请求,如下所示
export class UseAsyncServiceInterceptor implements HttpInterceptor {
constructor( private asyncService: AsyncService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// make apply logic function synchronous
this.someService.applyLogic(req).subscribe((modifiedReq) => {
const newReq = req.clone(modifiedReq);
// do not return it here because its a callback function
});
return next.handle(newReq); // return it here
}
}
使用Angular 6.0和RxJS 6.0在HttpInterceptor中进行异步操作 auth.interceptor.ts
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/index';;
import { switchMap } from 'rxjs/internal/operators';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.auth.client().pipe(switchMap(() => {
return next.handle(request);
}));
}
}
auth.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable()
export class AuthService {
constructor() {}
client(): Observable<string> {
return new Observable((observer) => {
setTimeout(() => {
observer.next('result');
}, 5000);
});
}
}
如果我的问题是正确的,那么你可以使用deffer拦截你的请求
module.factory('myInterceptor', ['$q', 'someAsyncService', function($q, someAsyncService) {
var requestInterceptor = {
request: function(config) {
var deferred = $q.defer();
someAsyncService.doAsyncOperation().then(function() {
// Asynchronous operation succeeded, modify config accordingly
...
deferred.resolve(config);
}, function() {
// Asynchronous operation failed, modify config accordingly
...
deferred.resolve(config);
});
return deferred.promise;
}
};
return requestInterceptor;
}]);
module.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
}]);