Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to observe the angular 5 interceptor error in some component

Hi I am new to angular 5 and followed some blogs to write the HTTP Interceptor.

export class AngularInterceptor implements HttpInterceptor {
public http404 = false;
constructor() { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    console.log("intercepted request ... ");

    // Clone the request to add the new header.
    const httpReq = req.clone(
        {
            headers: req.headers.set("headerName", "headerValue")
        }
    );

    console.log("Sending request with new header now ...");

    //send the newly created request
    return next.handle(httpReq)
        .catch((error, caught) => {
            //intercept the respons error and displace it to the console 
            console.log("Error Occurred");
            if(error.status === 404)
this.http404 = true;
//need to pass this value to another component. Let's say app.component.ts and display some message to the user.
            //return the error to the method that called it
            return Observable.throw(error);
        }) as any;
}

}

This is working fine. But what I need to do is to pass this error code to other components and print out a message on the screen for the user. One wy to do that is to create an observable but I am unable to implement that.

Any help is highly appreciated.

like image 802
rsisaudia Avatar asked Jan 28 '23 19:01

rsisaudia


1 Answers

You can use a service to do that, by leveraging a Subject. Here's an example of using BehaviourSubject.

First you create a service. This service will be shared across the two classes:

export class BroadcastService {
    public http404: BehaviorSubject<boolean>;

    constructor() {
        //initialize it to false
        this.http404 = new BehaviorSubject<boolean>(false);
    }
}

In your HttpInterceptor class, you inject the BroadcastService into it. To update the BehvaiourSubject, simply use .next():

export class AngularInterceptor implements HttpInterceptor {
    public http404 = false;

    constructor(public broadcastService: BroadcastService) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        console.log("intercepted request ... ");

        // Clone the request to add the new header.
        const httpReq = req.clone({
            headers: req.headers.set("headerName", "headerValue")
        });

        console.log("Sending request with new header now ...");

        //send the newly created request
        return next.handle(httpReq)
            .catch((error, caught) => {
                //intercept the respons error and displace it to the console
                console.log("Error Occurred");
                if (error.status === 404)
                    this.http404 = true;
                //need to pass this value to another component. Let's say app.component.ts and display some message to the user.
                this.broadcastService.http404.next(true);
                //return the error to the method that called it
                return Observable.throw(error);
            }) as any;
    }
}

And in your app.component.ts, simply subscribe it using .asObservable(). You need to inject it too:

export class AppComponent implements ngOnInit {
    constructor(public broadCastService: BroadcastService) {
    }

    OnInit() {
        this.broadCastService.http404.asObservable().subscribe(values => {
            console.log(values); // will return false if http error
        });
    }
}
like image 117
CozyAzure Avatar answered May 12 '23 00:05

CozyAzure