相关疑难解决方法(0)

如何在Angular2中订阅服务上的事件?

我知道如何使用EventEmitter引发事件.如果我有这样的组件,我还可以附加一个方法来调用:

<component-with-event (myevent)="mymethod($event)" />
Run Code Online (Sandbox Code Playgroud)

当我有这样的组件时,一切都很好.我将一些逻辑移动到服务中,我需要从服务内部引发一个事件.我做的是这样的:

export class MyService {
  myevent: EventEmitter = new EventEmitter();

  someMethodThatWillRaiseEvent() {
    this.myevent.next({data: 'fun'});
  }
}
Run Code Online (Sandbox Code Playgroud)

我有一个组件,需要根据此事件更新一些值,但我似乎无法使其工作.我试过的是这个:

//Annotations...
export class MyComponent {
  constructor(myService: MyService) {
    //myService is injected properly and i already use methods/shared data on this.
    myService.myevent.on(... // 'on' is not a method <-- not working
    myService.myevent.subscribe(.. // subscribe is not a method <-- not working
  }
}
Run Code Online (Sandbox Code Playgroud)

当引发它的服务不是一个组件时,我如何使MyComponent订阅该事件?

我在On 2.0.0-alpha.28上

编辑:修改我的"工作示例"实际工作,因此可以把重点放在不工作的部分;)

示例代码:http: //plnkr.co/edit/m1x62WoCHpKtx0uLNsIv

javascript angular

97
推荐指数
2
解决办法
12万
查看次数

标签 统计

angular ×1

javascript ×1