Angular 4捕获外部事件

时间:2017-05-03 13:24:22

标签: angular

如果我有此活动

API.onResourceStop.connect(function () {

});

如何在Angular上发射它?

1 个答案:

答案 0 :(得分:1)

Angular使用RxJs库发送事件。您需要创建一个回调的Observable。

  

创建一个新的Observable,当Observer订阅它时将执行指定的函数。

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-create

   const API= { 
     onResourceStop: 
     { 
       connect(fn) {
         setTimeout(()=> fn('connect'), 5000);
       }
     }
  };

  let observable = Rx.Observable.create( observer => {
    API.onResourceStop.connect(arg=>{
       observer.next(arg);
       observer.complete();
    });
  });
  observable.subscribe(
    value => console.log(value),
    err => {},
    () => console.log('this is the end')
  );