向 RxJs 6 订阅原型添加方法

Adding method to RxJs 6 Subscription prototype

使用 rxjs@5,我们实现了一个方便的 DisposeBag class 来收集订阅并在销毁 Angular 组件时更容易取消订阅。

import { Subscription } from "rxjs/Subscription";

export class DisposeBag {
    private _subscription: Subscription[] = [];

    insert(subscription: Subscription): void {
        this._subscription.push(subscription);
    }

    dispose() {
        this._subscription.forEach(subscription => {
            subscription.unsubscribe();
        });
        this._subscription = [];
    }
}

export function disposedBy(this: Subscription, bag: DisposeBag): void {
    bag.insert(this);
}

Subscription.prototype.disposedBy = disposedBy;

declare module "rxjs/Subscription" {
    interface Subscription {
        disposedBy: typeof disposedBy;
    }
}

升级到 rxjs@6 + rxjs-compat@6,我们得到以下编译错误:

(12) Property 'unsubscribe' does not exist on type 'Subscription'. (22) 'Subscription' only refers to a type, but is being used as a value here.

将第一个导入切换到

import { Subscription } from "rxjs";

解决了这两个错误,但引入了 (22) Property 'disposedBy' does not exist on type 'Subscription'. 错误。

我们该如何解决这个问题?

感谢 的回答,我能够像这样修复它:

import { Subscription } from "rxjs";

export class DisposeBag {
    private _subscription: Subscription[] = [];

    insert(subscription: Subscription): void {
        this._subscription.push(subscription);
    }

    dispose() {
        this._subscription.forEach(subscription => {
            subscription.unsubscribe();
        });
        this._subscription = [];
    }
}

export function disposedBy(this: Subscription, bag: DisposeBag): void {
    bag.insert(this);
}

Subscription.prototype.disposedBy = disposedBy;

declare module "rxjs/internal/Subscription" {
    interface Subscription {
        disposedBy: typeof disposedBy;
    }
}