【发布时间】:2020-02-16 15:38:22
【问题描述】:
我正在开发一个 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
}
}
现在我的疑问是,每当我在next.handle(req) 之后使用.pipe() 方法时,它都不会显示任何错误。代码如下:
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(()=>{
}));
}
}
但是每当我在next.handle() 之后使用.subscribe() 时,都会出错。
代码如下:
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,因此我们可以订阅它?
【问题讨论】:
-
intercept() 方法必须返回一个 Observable。 pipe() 将一个 Observable 转换为另一个 Observable,所以这是正确的。 subscribe()... 订阅 Observable 并返回 Subscription,而不是 Observable,所以这是不正确的。
-
为什么你认为他们会是一样的?仅仅因为您可以订阅某些东西并不意味着这总是正确的做法。
标签: angular typescript http angular-http-interceptors