根据Angular文档的介绍,在拦截器中使用'next.handle()”方法会返回一个可观察对象,而不是一个订阅对象。因此,拦截器中的订阅对象无法直接更新到调用'next.handle()”方法后返回的可观察对象中。要想实现这一功能,需要将订阅对象转换为可观察对象。
代码示例:
@Injectable() export class MyInterceptor implements HttpInterceptor { constructor(private authService: AuthService) {}
intercept(
req: HttpRequest
const subscription = next.handle(authReq).subscribe(
event => {
if (event instanceof HttpResponse) {
console.log('HttpResponse received.');
// do something with received response
}
},
err => {
console.error('HttpError:', err);
}
);
// convert Subscription to Observable
const obs = new Observable(subscriber => {
subscriber.add(subscription);
});
return obs;
} }
在以上的代码示例中,我们创建了一个Observable对象'obs”,并将Subscription对象'subscription”添加到其中,然后'obs”作为最终返回的可观察对象返回。这样一来,我们就可以更新订阅器中的数据到'obs”中,从而实现在拦截器中使用'next.handle()”方法时更新订阅数据的目的。