自定义cordova pushNotification包装器返回可观察对象



cordova的phonegap-plugin-push有以下语法的几个函数

function name(successCallback(),errorCallback(),options)

我想写一个包装函数并返回一个可观察对象,但是我有点卡在如何使用typescript为angular2创建它。

name.subscribe((data)=>{...},(err)=>{})

到目前为止,我主要只订阅了现有的可观察对象,如http.

所以应该是

public unregister(options):Observable<any>{
  if(window.PushNotification){
    window.PushNotification.ungregister(...)
  }
}

提前感谢您的帮助!!

您可以使用create或直接使用构造函数创建新的Observable

//Higher order function for binding a cordova style method to a method 
//that returns Observables
function bindCordovaCallback(fn) {
  //Returns a new function 
  return (...opts) => 
    Rx.Observable.create(observer => {
      // This assumes a single call to success will be made
      const nextCallback = (v) => { observer.next(v); observer.complete(); }
      const errCallback = (e) => observer.error(e);
      //Invoke the passed in method.
      fn(nextCallback, errCallback, ...opts);
      //Return empty unless you have some cancellation logic
      return Subscription.EMPTY;
    });
}
const nameObservable = bindCordovaCallback(name)(opts);
//Each subscribe will reinvoke the underlying method just like $http in angular2
nameObservable.subscribe(data => {...}, err => {...}

最新更新