Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何取消Angular2中的订阅_Javascript_Angular_Rxjs - Fatal编程技术网

Javascript 如何取消Angular2中的订阅

Javascript 如何取消Angular2中的订阅,javascript,angular,rxjs,Javascript,Angular,Rxjs,如何取消Angular2中的订阅?RxJS似乎有一个dispose方法,但我不知道如何访问它。所以我有可以访问EventEmitter并订阅它的代码,如下所示: var mySubscription = someEventEmitter.subscribe( (val) => { console.log('Received:', val); }, (err) => { console.log('Received error:',

如何取消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();
编辑:这不适用于RxJS 5,angular2正在使用RxJS 5。 我原以为您正在寻找上的dispose方法

subscribe方法返回一个一次性()

我似乎无法在文档中更明确地找到它,但这是有效的():

奇怪的是,退订似乎对你有效,而对我无效…

使用

if(mySubscription){
  mySubscription.unsubscribe();
}

宁愿在销毁组件的同时取消订阅rxjs unsubscribe's,即从DOM中删除以避免不必要的内存泄漏

对于ng2的观测值取消订阅有太多不同的解释,我花了很多时间才找到正确的答案。下面是一个工作示例(我试图限制mousemove)

从“@angular/core”导入{Injectable,OnDestroy};
从“rxjs”导入{Subscription};
@可注射()
导出类MyClass实现OnDestroy{
mouseSubscription:Subscription;//为您的订阅设置一个变量
myFunct(){
//我正试图阻止老鼠移动
const eachSecond$=可观测计时器(0,1000);
const mouseMove$=Observable.fromEvent(文档“mouseMove”);
const mouseMoveEachSecond$=mouseMove$.sample(每秒钟$);
this.mouseSubscription=mouseMoveEachSecond$.subscribe(()=>this.doSomethingElse());
}
doSomethingElse(){
log(“鼠标移动”);
}
停止(){
this.mouseSubscription.unsubscribe();
}
恩贡德斯特罗(){
this.mouseSubscription.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<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();
        });
    }
}

我个人更喜欢使用主题来关闭组件在销毁生命周期步骤中可能拥有的所有订阅,这可以通过以下方式实现:

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();
  }
}
从'@angular/core'导入{Component};
从“rxjs/Rx”导入{Subject};
@组成部分({
选择器:“某些类应用程序”,
templateUrl:'./someClass.component.html',
提供者:[]
})
导出类SomeClass{
private ngUnsubscribe:Subject=new Subject();//当组件被销毁时,此主题将通知每个订阅停止。
//**********
构造函数(){}
恩戈尼尼特(){
this.http.post(“SomeUrl.com”,{},null).map(响应=>{
console.log(“耶”);
}).takeUntil(this.ngUnsubscribe).subscribe();//在这里,每当组件被销毁时,您都会告诉订阅停止。
}
恩贡德斯特罗(){
//这是我们关闭任何活动订阅的地方。
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}

推荐的方法是使用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();
    }
}
您可以从“rxjs”中找到主题

import{Subject}的详细说明;
从“rxjs/operators”导入{takeUntil};
从“../some_文件/SomeAPIService.service.ts”导入{SomeAPIService}
@组成部分({
templateUrl:“./your_Page.html”,
样式URL:['./您的_Styles.scss']
})
导出类(您的类)实现OnInit、OnDestroy{
//这是一个最简单形式的主题变量
私人退订$=新科目();
构造函数(私有someAPIService:someAPIService){}
ngOnit():void{
this.someAPIService.getToList({id:1})
.pipe(takeUntil(此.unsubscribe$))
.subscribe((值:SomeVariable)=>{
//您需要的任何值都是可变的
},)
}
ngOnDestroy():void{
//清除所有页面订阅
此。取消订阅$.next();
此.unsubscribe$.complete();
}
`}

天哪。我发誓我已经试过了。我查看了RxJS源代码,它似乎就是这样。我一定是因为另一个错误导致了我的问题。谢谢。这很有效,但我很好奇TypeScript中的
mySubscription
是什么类型。我想避免在我的类中编写
mySubscription:any
。@paradite
import{Subscription}来自“rxjs”和用于取消订阅
如果(!mySubscription.closed){mySubscription.unsubscripte();}
从“rxjs/Subscription”导入{Subscription}
将有助于减小软件包大小。您可能会使用不同的版本。Angular2在Rxjs5上,不是吗?是的,Angular2使用Rxjs5。就是这样。可以找到。修改是为了符合FYI的要求——如果你要做反应性的事情,使用一个主题,而不是Angular的EventEmitter——不能保证它仍然是主题的超类。仅对@Output事件使用EventEmitter。实际上应该是
如果(!mySubscription.closed){mySubscription.unsubscribe();}
我也使用它,它可以很好地扩展组件中的更多订阅。没有“魔力”-这是设计的:“订阅也可以放在一起,以便调用unsubscripte()一个订阅的用户可能会取消多个订阅。您可以通过将一个订阅“添加”到另一个订阅中来做到这一点:“您可能会对另一种明确的方法感兴趣。使用
takeWhile
操作符。这里描述的方法:检查一个,它使用takeUntil。有一个丰富而有趣的讨论,考虑了不同的选择;在ngondestory()方法中?
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();
    }
}
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();
  }
}
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();
    }
}
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { SomeAPIService } from '../some_file/someAPIService.service.ts

@Component({
  templateUrl: './your_Page.html',
  styleUrls: ['./your_Styles.scss']
})

export class (your class) implements OnInit, OnDestroy {
   // This is a subject variable at it simplest form 
     private unsubscribe$ = new Subject<void>();

     constructor (private someAPIService : SomeAPIService) {}
   
     ngOnit(): void { 
       this.someAPIService.getTODOlist({id:1})
        .pipe(takeUntil(this.unsubscribe$))
         .subscribe((value: SomeVariable) => {
         // What ever value you need is SomeVariable
      },)
    }


     ngOnDestroy(): void {
    // clears all, page subscriptions 
      this.unsubscribe$.next();
      this.unsubscribe$.complete();
     }
`}