gpt4 book ai didi

angular - 如何将异步服务用于 Angular httpClient 拦截器

转载 作者:太空狗 更新时间:2023-10-29 17:18:54 29 4
gpt4 key购买 nike

使用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. */
}
}

响应的不同问题,但我需要再次应用逻辑以更新响应。在这种情况下, Angular 指南建议如下所示:

return next.handle(req).do(event => {
if (event instanceof HttpResponse) {
// your async elaboration
}
}

但是“do() 运算符——它在不影响流值的情况下为 Observable 添加了副作用”。

Solution: the solution about request is shown by bsorrentino (into accepted answer), the solution about response is the follow:

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);
});
}
});
});

那么,如何将带有async服务的request和response修改为httpClient拦截器呢?

Solution: taking advantage of 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));
}
}

关于angular - 如何将异步服务用于 Angular httpClient 拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45345354/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com