【发布时间】:2019-03-24 15:21:02
【问题描述】:
我正在尝试编写一个全局 HTTP 拦截器,它拦截所有 HTTP 响应、检查响应并(如果满足某些条件)显示一个快餐栏。
我似乎无法显示小吃店。如果我在 .open() 行设置断点,我会看到小吃栏出现片刻,但没有任何文本且偏离中心。
拦截器:
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");
});
}
}
我已尝试取出该区域,但不使用注射器。没有变化。
【问题讨论】:
标签: angular angular-material angular6 snackbar