管道和订阅之间的实际区别是什么?

时间:2019-10-20 08:22:54

标签: angular typescript http angular-http-interceptors

我正在开发HttpInterceptor。为了开发此拦截器,我正在创建一个服务类,如下所示:

df = df.reset_index()

现在,我的疑问是,每当在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()返回了一个Observable,所以我们可以订阅它?

2 个答案:

答案 0 :(得分:1)

pipe()命令用于通过一系列不同的处理命令(称为运算符)运行Observable的结果。最终的回报仍然是ObservableThis is a good explanation of what pipeable operators are。我的简称是管道运算符是用于处理Observable结果的函数。

subscribe()命令用于获取Observable的结果,并返回Subscription

订阅与可观察项不同,这就是为什么它们不能互换使用的原因。可能值得注意的是,如果没有subscribe(),则可管道运算符将永远不会对Observable返回的结果执行。

答案 1 :(得分:1)

订阅时,结果将在函数中返回

pipe()返回一个可观察的对象,您可以订阅 pipe()允许您处理原始的可观察对象,以便您在订阅原始观察对象时获得的值与原始可观察对象发出的值不同

就像管道一样,pipe()在值到达您订阅的值之前进行某种处理