目的
在web页面经常会使用到弹对话框功能,如对机器上报的错误码的处理,因此将其封装为一个service,便于管理、使用。
通常故障码定义如下:
<ERROR>
<Device>1</Device>
<Code>-21</Code>
<Description>当前热容量太小,需要预热</Description >
</ERROR>
// 以上分别为:设备类型,故障码,故障描述信息
官网API(modal-zorro)
对话框分为2种模式:
- 普通模式。即:NzModalService.create(options)
- 确认框模式。通过调用
confirm/info/success/error/warning
弹出。// 例子 this.modal.comfirm({ nzMask: false, nzTitle: `Test ${method} title`, nzContent: `Test content: <b>${method}</b>`, nzStyle: { position: 'absolute', top: `${pos * 70}px`, left: `${pos++ * 300}px` } })
通过服务方式
NzModalService.xxx()
创建的对话框,都会返回一个NzModalRef
对象。
封装
export enum DialogType {
Hint = "hint",
Warning = "warning",
Error = "error",
}
export interface DialogModal {
type: DialogType;
content?: string;
title?: string;
onOK?: never | OnClickCallback<any>;
onCancel?: never | OnClickCallback<any>;
lifeCycle?: number;
}
// 因为这个服务将在很多个component里用到,所以在全局中注入
export class ToastAndModalService {
constructor(private modalService: NzModalService) {}
// 未封装直接使用modalService:
// this.modalService.success({
// nzTitle: "This is a notification message",
// nzContent: "This modal will be destroyed after 1 second",
// });
private assembleSimple(message: SimpleModalMessage) {
return {
// 未写完全
nzOnOK: message.parameters.onOK,
nzOnCancel: message.parameters.onCancel,
nzVisible: message.visible,
nzTitle: message.parameters.title,
nzClosable: message.closable,
nzMaskClosable: false, //
nzContent: message.parameters.content,
};
}
modalTypeToSimpleModalType(data: DialogModal): SimpleModalMessage {
// 把Modal Type转化为Simpel Modal
let newType: ModalBaseType = ModalBaseType.info;
if (data.type === DialogType.Hint) {
newType = ModalBaseType.confirm;
} else if (data.type === DialogType.Error) {
newType = ModalBaseType.error;
} else {
newType = ModalBaseType.warn;
}
const newModal = {
parameters: {
type: newType,
content: !!data.content ? data.content : "",
title: !!data.title ? data.title : undefined,
onOK: !!data.onOK
? data.onOK
: () => {
console.log("onOk");
},
onCancel: !!data.onCancel
? data.onCancel
: () => {
console.log("onCancel");
},
},
lifeCycle: data.lifeCycle ? data.lifeCycle : undefined,
};
return newModal;
}
createSimpleModalOf(message: SimpleModalMessage) {
let ref: NzModalRef = this.modalService[message.parameters.type](
this.assembleSimple(message)
);
return ref;
}
createModalOfType(data: DialogModal): NzModalRef {
const simpleModal = this.createSimpleModalOf(
this.modalTypeToSimpleModalType(data)
);
return simpleModal;
}
getHandler(code: DialogContent): DialogModal {
const models: { model: DialogModal }[] = [
{
model: {
type: DialogType.Warning,
content: "test 1",
},
},
{
model: {
type: DialogType.Warning,
content: "test 2",
},
},
];
let modalParam = models.find((item) => {
item.model.content === code;
});
if (modalParam) {
return modalParam.model as DialogModal;
}
}
closeAll() {
this.modalService.closeAll();
}
}