【发布时间】:2018-12-25 02:15:52
【问题描述】:
我是 TypeScript 新手。
在一个 Angular 项目中,我正在准备一个 SnackBar 服务以通知用户。
我有一些 Java 背景。
我有两个问题。
在 TypeScript 中定义一个类时,我不能使用“const”关键字。而且我的服务将是一个单例,所以如果它在某个地方意外地改变了我的价值,我的整个应用程序就会崩溃。因此,我尝试了私人领域。但我认为这还不够。
1) TypeScript 可以为我们提供类似于 const 的类字段吗?
为我服务:
import {Injectable} from '@angular/core';
import {MatSnackBar} from '@angular/material';
@Injectable({
providedIn: 'root'
})
export class SnackService {
private DURATION = 1800;
private HORIZANTAL_POSITION = 'end';
constructor(private sncackBar: MatSnackBar) {
}
successful(message: string) {
this.sncackBar.open(message, null, {
duration: this.DURATION,
horizontalPosition: this.HORIZANTAL_POSITION,
panelClass: 'success-snackBar'
});
}
error(message: string) {
this.sncackBar.open(message, null, {
duration: this.DURATION,
horizontalPosition: this.HORIZANTAL_POSITION,
panelClass: 'error-snackBar'
});
}
}
2) 由于“类型别名”,我的代码无法编译。我如何将 const 值用于“类型别名”?
上面的类没有编译,消息是:
error TS2345: Argument of type '{ duration: number; horizontalPosition: string; panelClass: string; }' is not assignable to parameter of type 'MatSnackBarConfig<any>'.
Types of property 'horizontalPosition' are incompatible.
但在“MatSnackBarConfig”中,“MatSnackBarHorizontalPosition”已经是一个字符串了。
export declare type MatSnackBarHorizontalPosition = 'start' | 'center' | 'end' | 'left' | 'right';
【问题讨论】:
-
你可以简单地检查
MatSnackBarConfig<any>实际上是什么,然后应该解决第二个问题 -
您需要导入 MatSnackBarHorizontalPosition 并将此类型分配给您的私有 HORIZONTAL_POSITION 值
-
你在 this.sncackBar 中有一个错字
-
单例可以保存在静态类字段中,以后可以确保构造函数中没有单个实例已经实例化
-
如果您将变量名大写,因为您希望它们是常量,您可以使用
readonly修饰符
标签: angular typescript angular-material2