【发布时间】:2020-09-10 03:06:35
【问题描述】:
我在我的 Angular 应用程序中创建了一个全局的snackBarService。我想根据消息类型(错误、成功、警告等)自定义panelClass。我采用的方法是在构造函数中进行全局配置,这有助于为小吃店定义全局样式/配置,并将添加自定义类以根据消息类型更改背景颜色。
SnackBarService.ts
import { Injectable, NgZone } from "@angular/core";
import { MatSnackBar, MatSnackBarConfig } from "@angular/material";
@Injectable({
providedIn: "root",
})
export class SnackbarService {
private config: MatSnackBarConfig;
constructor(private snackbar: MatSnackBar, private zone: NgZone) {
this.config = new MatSnackBarConfig();
this.config.panelClass = ["snackbar-container"];
this.config.verticalPosition = "top";
this.config.horizontalPosition = "right";
this.config.duration = 4000;
}
error(message: string) {
this.config.panelClass = ["snackbar-container", "error"];
this.show(message);
}
success(message: string) {
this.config.panelClass = ["snackbar-container", "success"];
this.show(message);
}
warning(message: string) {
this.config.panelClass = ["snackbar-container", "warning"];
this.show(message);
}
private show(message: string, config?: MatSnackBarConfig) {
config = config || this.config;
this.zone.run(() => {
this.snackbar.open(message, "x", config);
});
}
}
app.scss
.snackbar-container {
margin-top: 70px !important;
color: beige;
&.error {
background-color: #c62828 !important;
}
&.success {
background-color: #2e7d32 !important;
}
&.warning {
background-color: #ff8f00 !important;
}
}
从组件中我将使用这样的服务
this.snackbarService.success("This message is from snackbar!!!");
以上代码完美运行。
但是,
由于panelClass没有.push方法,我无法添加动态类,因此我每次都需要像this.config.panelClass = ["snackbar-container", "error"];这样复制全局类
error(message: string) {
this.config.panelClass.push("error"); // this throws error in typescript
this.show(message);
}
有没有更好的方法来解决这个问题?
【问题讨论】:
标签: javascript angular angular-material snackbar