Egg*_*ggy 26 rxjs eventemitter angular2-services rxjs5 angular
// Part of service
public someEvent: EventEmitter<number> = new EventEmitter();
....
// Component
@Component({
selector: 'some-component',
template: `...`
})
export class SomeComponent {
constructor(public service: Service) {
this.service.someEvent.subscribe((x) => {
// Do something
});
}
}
Run Code Online (Sandbox Code Playgroud)
SomeComponent在/路线中显示.当我在我的应用程序中导航到不同的路径并再次返回时,SomeComponent将再次订阅该事件,导致回调触发两次.如何订阅一次事件或取消订阅组件的破坏并再次订阅?
// Can't subscribe after.
ngOnDestroy() {
this.service.someEvent.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
sdg*_*uck 36
一个调用subscribe返回一个实例Disposable,它有一个方法dispose.
或者,如果您使用的是RxJS 5,dispose则已重命名为unsubscribe(感谢@EricMartinez).
并从RxJS文档:
...当我们不再有兴趣接收数据时,我们会在订阅时调用dispose.
存储您的通话结果,subscribe然后在其中处理订阅ngOnDestroy.
RxJS 5:
export class SomeComponent {
constructor (public service: Service) {
this.subscription = this.service.someEvent.subscribe((x) => {...});
}
ngOnDestroy () {
this.subscription.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
RxJS <5:
export class SomeComponent {
constructor (public service: Service) {
this.subscription = this.service.someEvent.subscribe((x) => {...});
}
ngOnDestroy () {
this.subscription.dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18797 次 |
| 最近记录: |