如何解决Angular构建失败时Angular2-Notification的NotificationType参数错误
错误原因
这个报错是TypeScript类型校验不通过导致的:create方法的第三个参数要求传入NotificationType枚举类型值,你当前传的是普通字符串字面量,二者类型不匹配。
修复方案
方案1:导入并使用枚举值(最规范)
在组件文件中先导入NotificationType枚举,调用时传入枚举成员即可:
// 顶部导入增加NotificationType import { NotificationsService, NotificationType } from 'angular2-notifications'; // 调用处修改为枚举值 ngOnInit() { this.notificationsService.create("Covering Letter", 'Covering Letter is required', NotificationType.Error, 'yes'); this.notificationsService.create("Covering Letter", 'Covering Letter is required', NotificationType.Success, 'yes'); this.notificationsService.create("Covering Letter", 'Covering Letter is required', NotificationType.Warn, 'yes'); }
方案2:直接使用库提供的快捷方法(更简便)
NotificationsService已经封装了对应类型的快捷调用方法,不需要走通用的create方法,代码更简洁:
ngOnInit() { this.notificationsService.error("Covering Letter", 'Covering Letter is required', 'yes'); this.notificationsService.success("Covering Letter", 'Covering Letter is required', 'yes'); this.notificationsService.warn("Covering Letter", 'Covering Letter is required', 'yes'); }
方案3:字符串类型断言(不推荐,仅临时应急用)
如果不想改动现有调用逻辑,可以给字符串增加类型断言,告诉TypeScript该字符串符合NotificationType类型定义:
this.notificationsService.create("Covering Letter", 'Covering Letter is required', 'error' as NotificationType, 'yes');
内容的提问来源于stack exchange,提问作者Anand Kenta
相关产品推荐
相关产品推荐

