JHipster 4.9.0:如何配置JhiAlertService的消息显示时长?
在JHipster 4.9.0中给JhiAlertService的消息指定显示时长
嘿,刚好对JHipster 4.9.0的JhiAlertService比较熟悉,来给你拆解下怎么自定义消息的显示时长~
1. 单个消息直接指定时长
JhiAlertService的快捷方法(比如success、error、info、warn)其实都支持传入timeout参数,用来覆盖默认的显示时长。参数顺序是:(message: string, params?: any, keepAfterRouteChange?: boolean, timeout?: number)
举个实际的例子:
// 显示带参数的成功消息,时长5秒(5000毫秒) this.jhiAlertService.success( 'entity.saved', // 从i18n文件读取的消息key { name: '订单' }, // 替换消息中占位符的参数 false, // 路由跳转后是否保留消息(false表示不保留) 5000 // 自定义显示时长,单位毫秒 );
如果不需要参数和路由保留设置,也可以简化成:
// 直接显示文本消息,时长10秒 this.jhiAlertService.success('操作已完成', {}, false, 10000);
2. 全局修改默认显示时长
如果你的项目里大部分消息都需要统一的时长,可以全局修改JhiAlertService的默认超时时间。
在你的app.module.ts里,通过自定义provider来调整:
import { JhiAlertService } from 'ng-jhipster'; import { ToastrService } from 'ngx-toastr'; import { TranslateService } from '@ngx-translate/core'; @NgModule({ providers: [ { provide: JhiAlertService, useFactory: (toastrService: ToastrService, translateService: TranslateService) => { const alertService = new JhiAlertService(toastrService, translateService); alertService.defaultTimeout = 6000; // 全局默认设置为6秒 return alertService; }, deps: [ToastrService, TranslateService] } ] }) export class AppModule {}
这样之后,如果你调用方法时没有传timeout参数,就会使用这个全局默认值;如果传了,会优先使用你传入的时长。
小提示
- timeout的单位是毫秒,比如
3000就是3秒,0的话消息不会自动消失(需要用户手动关闭) keepAfterRouteChange设为true时,即使页面跳转,消息也会保留到新页面,这个参数可以根据需求搭配timeout使用
内容的提问来源于stack exchange,提问作者Orn Arnar
相关产品推荐
相关产品推荐

