2017-03-25 52 views
4

试图将swal的第一个promise函数转换为observable并尝试使用cancel操作。有人可以帮助我的语法PLS。将Promise转换为Observable

swal({ 
    title: 'Are you sure?', 
    text: "You won't be able to revert this!", 
    type: 'warning', 
    showCancelButton: true, 
    confirmButtonColor: '#3085d6', 
    cancelButtonColor: '#d33', 
    confirmButtonText: 'Yes, delete it!', 
    cancelButtonText: 'No, cancel!', 
    confirmButtonClass: 'btn btn-success', 
    cancelButtonClass: 'btn btn-danger', 
    buttonsStyling: false 
}).then(function() { 
    swal(
    'Deleted!', 
    'Your file has been deleted.', 
    'success' 
) 
}, function (dismiss) { 
    // dismiss can be 'cancel', 'overlay', 
    // 'close', and 'timer' 
    if (dismiss === 'cancel') { 
    swal(
     'Cancelled', 
     'Your imaginary file is safe :)', 
     'error' 
    ) 
    } 
}) 

到目前为止,我有以下几点:

export class DialogService { 
    confirm(title: string, message: string):Observable<any> { 
     return Observable.fromPromise(swal({ 
      title: title, 
      text: message, 
      type: 'warning', 
      showCancelButton: true 
     })); 
    }; } 

如何添加function (dismiss)功能在上面?

回答

2

我不确定swal使用原生Promise API,我认为它使用JavaScript的承诺库如q或其他东西。

export class DialogService { 
    confirm(title: string, message: string):Observable<any> { 
     return Observable.create((observer: any) => { 
       swal({ 
        title: title, 
        text: message, 
        type: 'warning', 
        showCancelButton: true 
       }).then((data)=>{ 
        observer.next(data); 
       },(reason)=>{ 
        observer.error(reason); 
       }) 
      }) 
    } 
} 
2

NVM,我结束了以下..

return Observable.create((observer) => { 
     if (component.isUntouched()) { 
      observer.next(true); 
     } else { 
      swal({ 
       title: 'Sure?', 
       text: 'Not saved, are you sure?', 
       type: 'warning', 
       showCancelButton: true 
      }).then(() => { 
       observer.next(true); 
      },() => { 
       observer.next(false); 
      }) 
     } 
    }); 

只是为了完整起见,component.isUntouched()定义如下:

@ViewChild('appForm') appForm: NgForm; 
... 
isFormTouched():boolean{ 
    return this.eventForm.dirty; 
} 

而且在模板/ html中:

<form class="form form-horizontal" (ngSubmit)="submitEvent()" #appForm="ngForm"> 
    .. 
</form> 
相关问题