在服务和Inject中定义甜蜜警报

时间:2017-08-10 04:47:48

标签: typescript sweetalert

对angularJS2 / typescript中的警报消息使用甜蜜警报。由于它在应用程序中的多个位置使用,因此在许多地方重复使用此代码。

创建了一项服务

@Injectable()
export class AlertMessageService {



    constructor(private http: Http) {

     }

   public deleteMessage(){
    return swal({
      title: 'Are you sure?',
      text: "Delete the selected record(s)?",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#66c378',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes'
    })
    }

尝试在像这样的组件中使用它,这是行不通的。

  this.alertMessageService.deleteMessage.then(() => {
      if (ind !== -1 && ind != undefined) {
        this.attachments.splice(ind, 1);
      }
      /* let headers = new Headers();
        this.http.delete(AppUtils.INCIDENT_ATTACHMENT_URI+"/? path" + "=" + item.filePath,  {})
              .map(response => response.json().result)
              .catch(this.handleError);*/
    });
  }

我们是否有任何方法可以在服务中定义不同类型的警报类型并注入它,如何?

1 个答案:

答案 0 :(得分:0)

sweetalert.service.ts

import { Injectable } from '@angular/core';
import swal from 'sweetalert2';
@Injectable()
export class SweetAlertService {
constructor() { }
public warningAlert(textLine, isShowCancel?) {
return swal({
  title: textLine || 'Are you sure?',
  type: 'warning',
  showCancelButton: isShowCancel,
  cancelButtonText: 'No',
  confirmButtonText: isShowCancel ? 'Yes' : 'Ok',
  reverseButtons: true,
  allowOutsideClick: false
});
}
}

在component.ts

constructor(public sweetAlertService: SweetAlertService){}
const popupResponse =  this.sweetAlertService.warningAlert('Your meassage', true);

   if (popupResponse.value) {
   // press Yes on popup
    }
   else{// press cancel on popup}

在module.ts

import providers: [SweetAlertService ]

相关问题