使用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
答案 0 :(得分:8)
我认为被动流存在问题。方法拦截期望返回 Observable ,并且您必须使用<返回的 Observable 展平您的异步结果强> next.handle 强>
试试这个
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
答案 1 :(得分:3)
如果需要在拦截器中调用异步函数,则可以使用rxjs
from
运算符遵循以下方法。
import { MyAuth} from './myauth'
import { from } from 'rxjs'
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: MyAuth) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
// convert promise to observable using 'from' operator
return from(this.handle(req, next))
}
async handle(req: HttpRequest<any>, next: HttpHandler) {
// if your getAuthToken() function declared as "async getAuthToken() {}"
await this.auth.getAuthToken()
// if your getAuthToken() function declared to return an observable then you can use
// await this.auth.getAuthToken().toPromise()
const authReq = req.clone({
setHeaders: {
Authorization: authToken
}
})
// Important: Note the .toPromise()
return next.handle(authReq).toPromise()
}
}
答案 2 :(得分:1)
上面的答案似乎很好。我有相同的要求,但由于在不同的依赖项和运算符中进行更新而遇到了问题。花了我一些时间,但我找到了解决此特定问题的有效解决方案。
如果您使用的是Angular 7和RxJs 6+及更高版本的异步拦截器请求,则可以使用此代码,该代码适用于最新版本的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);
}));
}));
答案 3 :(得分:1)
我在拦截器中使用的是异步方法,如下所示:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
public constructor(private userService: UserService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.handleAccess(req, next));
}
private async handleAccess(req: HttpRequest<any>, next: HttpHandler):
Promise<HttpEvent<any>> {
const user: User = await this.userService.getUser();
const changedReq = req.clone({
headers: new HttpHeaders({
'Content-Type': 'application/json',
'X-API-KEY': user.apiKey,
})
});
return next.handle(changedReq).toPromise();
}
}
答案 4 :(得分:0)
好的我正在更新我的答案, 您无法在异步服务中更新请求或响应,您必须像这样同步更新请求
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
}
}
答案 5 :(得分:0)
使用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);
});
}
}
答案 6 :(得分:-2)
如果我的问题是正确的,你可以使用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');
}]);