I am trying to write a Global HTTP Interceptor which intercepts all HTTP Responses,inspects the responses and (if certain conditions are met), show a snackbar.
I cant seem to get the snackbar to show. If I put a breakpoint at the .open() line, i see the snackbar appear for a brief moment but without any text and off-center.
Interceptor:
import { Injectable, Injector, NgZone } from '@angular/core';
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
HttpResponse,
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { MatSnackBar } from '@angular/material';
//import { of } from 'rxjs/observable/of';
@Injectable()
export class TMCErrorHttpInterceptor implements HttpInterceptor {
constructor(public snackBar: MatSnackBar,private injector: Injector, private zone: NgZone){}
/**
* @param HttpRequest<any> request - The intercepted request
* @param HttpHandler next - The next interceptor in the pipeline
* @return Observable<HttpEvent<any>>
*/
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
return next.handle(request)
// add error handling
.pipe(
tap(event => {
if (event instanceof HttpResponse) {
if (this.isError(event.body)){
this.handleError(event.body);
}
}
}, error => {
console.error('NICE ERROR', error)
})
);
}
isError(response: any): any {
return (typeof (response) == "object"
&& typeof (response.MESSAGE) != "undefined"
&& typeof (response.STATUS) != "undefined"
&& typeof (response.CODE) != "undefined"
&& response.STATUS === "error"
);
}
handleError(error: any): any {
this.snackBar = this.injector.get(MatSnackBar);
this.zone.run(() => {
this.snackBar.open("hiiiiii");
});
}
}
I have tried taking out the zone, and not using the injector. No change.