Angular 2取消订阅 - 主题没有观察员

时间:2018-01-10 09:41:38

标签: angular

在实施取消订阅时,我看到了this回答。

我正在提到所提到的解决方案,但想了解以下内容:

如果我在'this.ngUnsubscribe.next()之前''console.log(this.ngUnsubscribe)',我看到它的观察者属性是一个包含0个项目的数组。

有意义吗?或者我错过了什么?

(在订阅之前我添加了takeUntil(this.ngUnsubscribe)当然)

----更新 - 添加了代码----

进口:

import "rxjs/add/operator/takeUntil"
import {Subject} from "rxjs/Subject"

类:

export class CarComponent{

    @Input() id;

    car:Car;

    ngUnsubscibe:Subject<boolean> = new Subject();

    constructor(private carsService:CarService){}

    ngOnInit(){
       this.carsService.getDetails(this.id)
            .takeUntil(this.ngUnsubscibe)
            .subscribe((car) => {this.car = car}, 
                       (err) => console.log(err)
                       );
    }

    ngOnDestroy(){
         //HERE - in the log, the object has property 'observers' 
         //of type array which the length of it is 0
         console.log(this.ngUnsubscibe);
         this.ngUnsubscibe.next(true);
         this.ngUnsubscibe.complete();
    }

}

1 个答案:

答案 0 :(得分:1)

现在我看到了这件事。您无需取消订阅Angular的Observables服务方法调用生成的http。它们会在您收到值时自动完成,因为它代表XHR调用,这显然是在ngOnDestroy工作时完成的。完成后,ngUnsubscribe Subject知道它监视的Observable已完成,因此无需手动取消订阅,因此ngUnsubscribe取消订阅源{ {1}}释放资源。 (因此Observable数组变空)

您只需取消订阅无法完成的observers即可。尝试使用此代码来查看差异:

Observables

因此,再一次 - 无需取消订阅export class CarComponent{ @Input() id; car:Car; ngUnsubscibe:Subject<boolean> = new Subject(); constructor(private carsService:CarService){} ngOnInit(){ this.carsService.getDetails(this.id) .takeUntil(this.ngUnsubscibe) .subscribe((car) => {this.car = car}, (err) => console.log(err) ); Observable.fromEvent(document.body, 'click').takeUntil(this.ngUnsubscribe) .subscribe(console.log) // so this is an Observable which listens to document clicks. As there //is no way to determine that a certain click was in fact the last, //we have to terminate it manually } ngOnDestroy(){ //HERE - in the log, the object has property 'observers', // and NOW it has length 1, as it contains the click listener Observable console.log(this.ngUnsubscibe); this.ngUnsubscibe.next(true); this.ngUnsubscibe.complete(); } } 来电http,因为它们会在收到数据时自动完成。 Angular中{em}需要手动终止的Observables的常见示例是对表单的Observable可观察的订阅,您编写的任何valueChanges来自传输数据一个组件/服务到另一个组件/服务,并且可能存储Observables类似Observables的东西,否则你可能会得到一堆“僵尸”ngrx,可能会导致内存泄漏。