Javascript 如何在 Angular2 中取消订阅
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34442693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cancel a subscription in Angular2
提问by Michael Oryl
How does one cancel a subscription in Angular2? RxJS seems to have a dispose method, but I can't figure out how to access it. So I have code that has access to an EventEmitter and subscribes to it, like this:
如何取消 Angular2 中的订阅?RxJS 似乎有一个 dispose 方法,但我不知道如何访问它。所以我有可以访问 EventEmitter 并订阅它的代码,如下所示:
var mySubscription = someEventEmitter.subscribe(
(val) => {
console.log('Received:', val);
},
(err) => {
console.log('Received error:', err);
},
() => {
console.log('Completed');
}
);
How can I use mySubscription
to cancel the subscription?
如何使用mySubscription
取消订阅?
回答by kendaleiv
Are you looking to unsubscribe?
您要取消订阅吗?
mySubscription.unsubscribe();
回答by Nightking
I thought I put in my two cents too. I use this pattern:
我以为我也投入了两美分。我使用这种模式:
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();
});
}
}
EDIT
编辑
I read the documentation the other day and found a more recommended pattern:
前几天我阅读了文档,发现了一个更推荐的模式:
Pros:
优点:
It manages the new subscriptions internally and adds some neat checks. Would prefer this method in the feature :).
它在内部管理新订阅并添加一些整洁的检查。在功能中更喜欢这种方法:)。
Cons:
缺点:
It isn't 100% clear what the code flow is and how subscriptions are affected. Nor is it clear (just from looking at the code) how it deals with closed subscriptions and if all subscriptions are getting closed if unsubscribe is called.
代码流是什么以及订阅如何受到影响并不是 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();
}
}
回答by Niklas Fasching
EDIT:This does not apply to RxJS 5, which is what angular2 is using.
编辑:这不适用于 RxJS 5,这是 angular2 使用的。
I would have thought you are looking for the dispose method on Disposable.
我原以为您正在寻找Disposable上的 dispose 方法。
the subscribe method returns a Disposable (link)
subscribe 方法返回一个 Disposable ( link)
I can't seem to find it more explicitly in the docs, but this works (jsbin):
我似乎无法在文档中更明确地找到它,但这有效(jsbin):
var observable = Rx.Observable.interval(100);
var subscription = observable.subscribe(function(value) {
console.log(value);
});
setTimeout(function() {
subscription.dispose();
}, 1000)
Weirdly, unsubscribe seems to be working for you while it's not working for me...
奇怪的是,取消订阅似乎对你有用,而对我不起作用......
回答by Joe Keene
Far too many different explanations of unsubscribe on Observables for ng2, took me ages to find the right answer. Below is a working example (I was trying to throttle mousemove).
关于取消订阅 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();
}
}
回答by Jahrenski
I prefer personally to use a Subject to close all subscriptions a component might have at the destroy life cycle step which can be achieved this way :
我个人更喜欢使用 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();
}
}
回答by Prithvi Uppalapati
ngOnDestroy(){
mySubscription.unsubscribe();
}
Prefer unsubscribing rxjs unsubscribe's while destroying the component i.e., removing from DOM for avoiding unecessary memory leaks
最好在销毁组件时取消订阅 rxjs 取消订阅,即从 DOM 中删除以避免不必要的内存泄漏
回答by Anshul
Use
用
if(mySubscription){
mySubscription.unsubscribe();
}
回答by yatharth varshney
The recommended approach is to use RxJS operators such as the takeUntiloperator. Below is the code snippet showing how to use it :-
推荐的方法是使用 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();
}
}
You can find a detailed explanation of the topic here
您可以在此处找到该主题的详细说明