puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Interceptor in Angular #95

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

image

Write an Interceptor

Here we write a sample, the browser will display a toast (angular material) when the server is down.

@Injectable()                                      <====
export class ServerErrorInterceptor implements HttpInterceptor {
    constructor(private readonly snackBar: MatSnackBar) {
    }

    public intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> {
        return new Observable((subscriber) => {
            next.handle(req).subscribe(
                (value) => subscriber.next(value),
                (error) => {
                    this.handleError(error, req, next, subscriber);
                },
            );
        });
    }

    private handleError<T>(error: HttpErrorResponse, req: HttpRequest<T>, next: HttpHandler, subscriber: Subscriber<HttpEvent<T>>) {
        const isServerError = Math.floor(error.status / 100) === 5;
        if (error.status === 0 || isServerError) {
            this.snackBar.open(
                'Server Error is happening',
                'Hide',
                { duration: 5000 },
            );
        }
    }
}

app.module.ts

const SERVER_ERROR_INTERCEPTOR: Provider = {
    multi: true,
    provide: HTTP_INTERCEPTORS,
    useExisting: forwardRef(() => ServerErrorInterceptor),
};

@NgModule({
     SERVER_ERROR_INTERCEPTOR,    <====
     ServerErrorInterceptor,                 <====
})
export class AppModule {
}

Reference

[1] https://angular.io/guide/http#http-interceptors