我是打字新手。
在一个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)由于“类型别名”,我的代码没有编译。“类型别名”如何使用常量值?
上面的类没有编译,消息是:
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';