无法读取 属性 'add'。 Rxjs 订阅

Cannot read property 'add'. Rxjs Subscription

我开始优化我的代码,我想在 ngOndestroy 中退订我的订阅。我有多个订阅。 问题是当我想调用 add() 方法来添加额外的子订阅时,它说无法读取未定义的 属性 'add'。 我在这里简化了我的代码,所以你只能看到重要的东西。

import {Subscription} from 'rxjs';

export class DashboardComponent implements OnInit, OnDestroy {
     private subscription: Subscription;
}

ngOnInit() {
   this.getData();
   this.getFeed();
}

ngOndestroy {
if (this.subscription) {
   this.subscription.unsubscribe();
   console.log(this.subscription);
   }
}

getData() {
   const subscription = this._authService.currentCompanyId.subscribe((newCompanyId) => {
            this.driverSubs(newCompanyId);
            this.vehicleSubs(newCompanyId);
        });
        this.subscription.add(subscription);
    }

   driverSubs(newCompanyId) {
        const subscription = this._driversService.getAllDrivers(newCompanyId).subscribe((data) => {
            this.getDataForDrivers(data);
        });
        this.subscription.add(subscription);
    }

    vehicleSubs(newCompanyId) {
        const subscription = this._vehiclesService.getAllVehicles(newCompanyId).subscribe((data) => {
            this.getDataForVehicles(data);
        });
        this.subscription.add(subscription);
    }
}

getFeed() {
    this.feedSubs();
    this.feedTachoSubs();
}

feedSubs() {
    const subscription = this._feedService.getFeed().subscribe(response => {
        this.feed = response;
    });
    this.subscription.add(subscription);
}

feedTachoSubs() {
    const subscription = this._feedTachoService.getFeedForVehicles().subscribe(response => {
        this.feedTacho = response;
    });
    this.subscription.add(subscription);
}

您的字段不应该是 private subscription: Subscription;,而是:

private subscriptions: Subscription[] = [];

-> 即数组。然后您将向其添加订阅:

this.subscriptions.push(subscription)

ngOnDestroy 中,您将不得不迭代该数组并取消订阅每个订阅:

for(const subscription of this.subscriptions) {
    subscription.unsubscribe();
}

另一种解决方案 - 虽然 Daniel 的答案可以解决问题,但他持有不同订阅对象的数组。
如果您只想持有 ONE 订阅,并且每当您取消订阅时,您希望所有订阅者也都取消订阅。
您只需创建它。

private subscriptions: Subscription;

然后,在构造函数中初始化对象:

this.subscriptions = new Subscription();

然后你可以使用:

this.subscriptions.add( ... Your subscription... );

当您想退订时:

if(this.subscriptions){
  this.subscriptions.unsubscribe();
}

所有子订阅也将取消订阅。
---
当您尝试 .add() 订阅时,您的主订阅未定义,这就是您无法添加新订阅的原因。

正如丹尼尔所说,您的 class 成员必须是一个订阅数组才能处理所有订阅。

除了他的回复,我建议尽可能使用 "async pipe",这样 angular 会自行取消订阅。