将Promise转换为Observable

时间:2017-03-25 17:28:33

标签: javascript angular typescript promise observable

尝试将swal的第一个promise函数转换为observable并尝试使用cancel操作。有人可以帮我解决语法问题。

/usr/bin/mysql -u USERNAME -p DATABASE_NAME --no-create-db < output.sql

到目前为止,我有以下内容:

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 })); }; } 功能?

3 个答案:

答案 0 :(得分:3)

我不确定swal是否使用原生Promise api,我认为它使用了q等JavaScript的承诺库。

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);
                 })
            })
     }
}

答案 1 :(得分:3)

订阅Observable后,您可以通过&#39; catch&#39;来自Promise的案例。

const subscription = Observable.fromPromise(...).subscribe(
  function () {
    console.log('Deleted!');
   },
  function (dismiss) {
    console.log('Dismiss', dismiss);
  })

请注意,只有当它是有效的Promises / A +规范时才会有效。

此处有更多信息:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/frompromise.md

答案 2 :(得分: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>