angular - SnackBar 在 HTTPInterceptor 中使用时不显示
问题描述
我正在尝试编写一个全局 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");
});
}
}
我试过取出该区域,而不是使用注射器。没变。
解决方案
所以我以某种方式偶然发现了答案,克隆请求使小吃店正常工作。奇怪的。
我理解从可修改性/可链接性的角度克隆请求的必要性,但要影响小吃店,需要比我更好的头脑来解释。
所以总而言之,对于那些徘徊在这个奇怪的森林尼克的人来说,将这一行添加到拦截()函数的顶部使其工作:
请求 = request.clone();
推荐阅读
- python - 在单个图中绘制多个饼图
- node.js - 数组 .split() 方法在 Heroku 应用程序中无法正常工作
- html - 在数据库中发布获取的数据
- javascript - 创建自定义复制按钮
- javascript - 将进程插入队列以异步工作
- azure-active-directory - 使用 Azure AD 作为 G Suite 的 IdP 时,无法登录同一域的多个帐户
- java - 需要使用java在url中获取域名后的值
- java - Intellij 和 Pycharm 注释显示固定的错误日期
- spring - 如何使用带有 Spring 的 Gradle 依赖管理插件的分类器的 dependencyManagement 版本?
- windows - 如何更改按钮的背景颜色并在其周围绘制焦点矩形?