Search code examples
angulartypescripthttpangular-http-interceptors

What is the actual difference between pipe and subscribe?


I am developing an HttpInterceptor. For developing this interceptor, I am creating a service class as shown below:

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

Now my doubt is that, whenever I use .pipe() method after next.handle(req) it doesn't show any error. Code is as follows:

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(()=>{

       }));
    }
}

But whenever I use .subscribe() after next.handle(), it gives error. The code is as follows:

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)=>{

       });
    }
}

And error we get when we subscribe is:

      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.

Why it is giving error when we subscribe() to next.handle(), because I have read that next.handle() returns an Observable hence we can subscribe it?


Solution

  • The pipe() command is used to run the results from an Observable through a bunch of different processing commands, called operators. The eventual return will still be an Observable. This is a good explanation of what pipeable operators are. My shortened version is that a pipeable operator is a function used to process an Observable's results.

    The subscribe() command is used to get the results of an Observable, and it returns a Subscription.

    A Subscription is not the same thing as an Observable, which is why they cannot be used interchangeably. It might be worth noting that Without a subscribe(), the pipeable operators will never execute on the results returned from the Observable.