我正在开发HttpInterceptor。为了开发此拦截器,我正在创建一个服务类,如下所示:
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
export class InterceptorClass implements HttpInterceptor{
intercept(req: HttpRequest<any>, next: HttpHandler){
debugger
req= req.clone({
headers: req.headers.append('currentPlace','New Delhi')
});
return next.handle(req); //Doubt in this line
}
}
现在,我的疑问是,每当在.pipe()
之后使用next.handle(req)
方法时,都不会显示任何错误。代码如下:
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
export class InterceptorClass implements HttpInterceptor{
intercept(req: HttpRequest<any>, next: HttpHandler){
debugger
req= req.clone({
headers: req.headers.append('currentPlace','New Delhi')
});
return next.handle(req).pipe(tap(()=>{
}));
}
}
但是,每当在.subscribe()
之后使用next.handle()
时,都会出错。代码如下:
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { map, tap } from 'rxjs/operators';
export class InterceptorClass implements HttpInterceptor{
intercept(req: HttpRequest<any>, next: HttpHandler){
debugger
req= req.clone({
headers: req.headers.append('currentPlace','New Delhi')
});
return next.handle(req).subscribe((data)=>{
});
}
}
订阅时得到的错误是:
Type '(req: HttpRequest<any>, next: HttpHandler) => Subscription' is not assignable to type '(req: HttpRequest<any>, next:
HttpHandler) => Observable<HttpEvent<any>>'.
Type 'Subscription' is missing the following properties from type 'Observable<HttpEvent<any>>': _isScalar, source, operator, lift, and 6 more.
为什么subscribe()
到next.handle()
时会出错,因为我已经读到next.handle()
返回一个Observable,因此我们可以订阅它?
pipe()
命令用于通过一系列不同的处理命令(称为运算符)运行Observable的结果。最终的回报仍然是Observable。 This is a good explanation of what pipeable operators are。我的简称是管道运算符是用于处理Observable结果的函数。
subscribe()
命令用于获取Observable的结果,并返回Subscription。
订阅与可观察对象不同,这就是为什么它们不能互换使用的原因。可能值得注意的是,如果没有subscribe()
,则可管道运算符将永远不会对Observable返回的结果执行。