[英]How use async service into angular httpClient interceptor
使用 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. */
}
}
響應的不同問題,但我需要再次應用邏輯以更新響應。 在這種情況下,角度指南建議如下:
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
如果您需要在攔截器中調用異步函數,則可以使用rxjs
from
運算符遵循以下方法。
import { MyAuth} from './myauth'
import { from, lastValueFrom } 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
}
})
return await lastValueFrom(next.handle(req));
}
}
我認為反應流存在問題。 方法intercept期望返回一個Observable ,你必須用next.handle返回的Observable來展平你的異步結果
嘗試這個
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.asyncService.applyLogic(req).mergeMap((modifiedReq)=> {
const newReq = req.clone(modifiedReq);
return next.handle(newReq);
});
}
您也可以使用switchMap而不是mergeMap
使用 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);
});
}
}
我在我的攔截器中使用了一個異步方法,如下所示:
@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();
}
}
上面的答案似乎很好。 我有相同的要求,但由於不同的依賴項和運算符的更新而面臨問題。 花了我一些時間,但我找到了一個解決這個特定問題的有效解決方案。
如果您使用 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
}
}
如果我的問題正確,那么您可以使用 defer 攔截您的請求
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'); }]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.