如何在Angular2中创建Dialog服务 [英] How to create a Dialog service in Angular2

查看:64
本文介绍了如何在Angular2中创建Dialog服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 2中,似乎任何和所有DOM操作都是由组件或指令执行的。我已经习惯了Angular 1,但是在某些服务中创建和管理自己的DOM元素是相当普遍的。最值得注意的是对话框。

In Angular 2 it seems any and all DOM manipulations are performed by components or directives. I'm used to Angular 1 however in which it was reasonably common to have certain services that created and managed their own DOM elements; most notably dialogs.

过去可以使用函数创建一个Angular 1服务 ConfirmationService 确认()返回 Promise< bool> ,向用户显示按下是或否的对话框,这解决了这个承诺。

In the past it was possible to for instance create an Angular 1 service ConfirmationService with a function Confirm() that returned a Promise<bool> that showed the user a dialog to press either yes or no on, which resolved the promise.

这些对话服务(例如 UI Bootstrap模式 NgDialog )通常通过注入 $ document $ compile $ parse 服务并创建和动态注入DOM元素。

These dialog services (for instance UI Bootstrap Modal or the NgDialog) generally work by injecting the $document, $compile and $parse services and create and inject DOM elements on the fly.

我很难找到推荐的Angular 2方法来创建这样的服务。如果可能的话,我想阻止必须创建一个 ConfirmationComponent ,它必须添加到需要确认的任何组件中(部分原因是它也可能是另一个需要确认的服务,确认只是一个有用的例子)

I'm having difficulties finding out what the recommended Angular 2 approach is to creating such a service. If at all possible I'd like to prevent having to create a ConfirmationComponent that has to be added to any component that needs to ask for confirmation (partly because it can also be another service that needs the confirmation and that confirmation is but one example where this is useful)

无论如何,一些帮助/指针将不胜感激。在此先感谢。

Anyway, some help/pointers would be greatly appreciated. Thanks in advance.

推荐答案

如果你可以依赖 sweetalert2 ,对话服务变得非常简单:

If you're ok taking a dependency on sweetalert2, a dialog service becomes pretty simple:

import { Injectable } from '@angular/core';
import { default as swal } from 'sweetalert2';

@Injectable()
export class DialogService {
    confirm(title: string, message: string) {
        return swal({
            title: title,
            text: message,
            type: 'warning',
            showCancelButton: true
        });
    };
}

这篇关于如何在Angular2中创建Dialog服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆