如何在Angular2中取消订阅?RxJS似乎有一个dispose方法,但我无法弄清楚如何访问它.所以我有代码可以访问EventEmitter并订阅它,如下所示:
var mySubscription = someEventEmitter.subscribe( (val) => { console.log('Received:', val); }, (err) => { console.log('Received error:', err); }, () => { console.log('Completed'); } );
我mySubscription
该如何取消订阅?
你想取消订阅吗?
mySubscription.unsubscribe();
我以为我也加了两美分.我使用这种模式:
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; @Component({ selector: 'my-component', templateUrl: 'my.component.html' }) export class MyComponent implements OnInit, OnDestroy { private subscriptions: Array= []; public ngOnInit(): void { this.subscriptions.push(this.someService.change.subscribe(() => { [...] })); this.subscriptions.push(this.someOtherService.select.subscribe(() => { [...] })); } public ngOnDestroy(): void { this.subscriptions.forEach((subscription: Subscription) => { subscription.unsubscribe(); }); } }
编辑
我前几天阅读了文档,发现了一个更推荐的模式:
ReactiveX/RxJS /认购
优点:
它在内部管理新订阅并添加一些简洁的检查.在功能:)中更喜欢这种方法.
缺点:
它不是100%清楚代码流是什么以及订阅如何受到影响.也不清楚(仅从查看代码)如何处理已关闭的订阅以及如果所有订阅在调用取消订阅时关闭.
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; @Component({ selector: 'my-component', templateUrl: 'my.component.html' }) export class MyComponent implements OnInit, OnDestroy { private subscription: Subscription = new Subscription(); public ngOnInit(): void { this.subscription.add(this.someService.change.subscribe(() => { [...] })); this.subscription.add(this.someOtherService.select.subscribe(() => { [...] })); } public ngOnDestroy(): void { /* * magic kicks in here: All subscriptions which were added * with "subscription.add" are canceled too! */ this.subscription.unsubscribe(); } }
我原以为你在寻找Disposable上的dispose方法.
subscribe方法返回一个Disposable(链接)
我似乎无法在文档中更明确地找到它,但这有效(jsbin):
var observable = Rx.Observable.interval(100); var subscription = observable.subscribe(function(value) { console.log(value); }); setTimeout(function() { subscription.dispose(); }, 1000)
奇怪的是,取消订阅似乎对你有用,而它对我不起作用......