如何在Angular2中取消订阅? RxJS似乎有一个dispose方法,但我无法弄清楚如何访问它。所以我有代码可以访问EventEmitter并订阅它,如下所示:
var mySubscription = someEventEmitter.subscribe(
(val) => {
console.log('Received:', val);
},
(err) => {
console.log('Received error:', err);
},
() => {
console.log('Completed');
}
);
如何使用mySubscription
取消订阅?
答案 0 :(得分:108)
你想取消订阅吗?
mySubscription.unsubscribe();
答案 1 :(得分:45)
我以为我也投入了两美分。我使用这种模式:
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<Subscription> = [];
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();
});
}
}
修改强>
我前几天阅读了文档,发现了一个更推荐的模式:
优点:
它在内部管理新订阅并添加一些简洁的检查。在该功能中更喜欢这种方法:)。
缺点:
它不是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();
}
}
答案 2 :(得分:9)
我原以为你在Disposable上寻找处理方法。
subscribe方法返回Disposable(link)
我似乎无法在文档中更明确地找到它,但这可行(jsbin):
{{1}}
奇怪的是,取消订阅似乎对你有用,虽然它不适合我...
答案 3 :(得分:4)
对于针对ng2的Observables取消订阅,有太多不同的解释,花了我很多年才找到正确的答案。下面是一个工作示例(我试图限制鼠标移动)。
import {Injectable, OnDestroy} from "@angular/core";
import {Subscription} from "rxjs";
@Injectable()
export class MyClass implements OnDestroy {
mouseSubscription: Subscription; //Set a variable for your subscription
myFunct() {
// I'm trying to throttle mousemove
const eachSecond$ = Observable.timer(0, 1000);
const mouseMove$ = Observable.fromEvent<MouseEvent>(document, 'mousemove');
const mouseMoveEachSecond$ = mouseMove$.sample(eachSecond$);
this.mouseSubscription = mouseMoveEachSecond$.subscribe(() => this.doSomethingElse());
}
doSomethingElse() {
console.log("mouse moved");
}
stopNow() {
this.mouseSubscription.unsubscribe();
}
ngOnDestroy() {
this.mouseSubscription.unsubscribe();
}
}
&#13;
答案 4 :(得分:2)
ngOnDestroy(){
mySubscription.unsubscribe();
}
首选在销毁组件时取消订阅rxjs unsubscribe,即从DOM中删除以避免不必要的内存泄漏
答案 5 :(得分:2)
我个人更喜欢使用Subject关闭组件在销毁生命周期步骤中可能具有的所有订阅,这可以通过这种方式实现:
import { Component} from '@angular/core';
import { Subject } from "rxjs/Rx";
@Component({
selector: 'some-class-app',
templateUrl: './someClass.component.html',
providers: []
})
export class SomeClass {
private ngUnsubscribe: Subject<void> = new Subject<void>(); //This subject will tell every subscriptions to stop when the component is destroyed.
//**********
constructor() {}
ngOnInit() {
this.http.post( "SomeUrl.com", {}, null ).map( response => {
console.log( "Yay." );
}).takeUntil( this.ngUnsubscribe ).subscribe(); //This is where you tell the subscription to stop whenever the component will be destroyed.
}
ngOnDestroy() {
//This is where we close any active subscription.
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
答案 6 :(得分:1)
使用
if(mySubscription){
mySubscription.unsubscribe();
}
答案 7 :(得分:1)
建议的方法是使用RxJS运算符,例如 takeUntil 运算符。以下是显示如何使用它的代码段: -
import { Component, OnInit, OnDestroy } from '@angular/core';
import { interval, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {
private ngUnsubscribe = new Subject();
constructor() { }
ngOnInit() {
var observable1 = interval(1000);
var observable2 = interval(2000);
observable1.pipe(takeUntil(this.ngUnsubscribe)).subscribe(x => console.log('observable1: ' + x));
observable2.pipe(takeUntil(this.ngUnsubscribe)).subscribe(x => console.log('observable2: ' + x));
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
您可以找到主题here
的详细说明答案 8 :(得分:-1)
const converter = celsius =>{
fahrenheit=(celsius*1.8)+32;
console.log(fahrenheit);
return fahrenheit;
};