Search code examples
angularangular7subscriptionrxjs6unsubscribe

Cannot read property 'add'. Rxjs Subscription


I started to optimize my code and i want to unsubscribe from my subscriptions in ngOndestroy. I have multiple subscription. The problem is when i want to invoke the add() method to add additional child subscriptions it says Cannot read property 'add' of undefined. I simplified my code here so you can see the important things only.

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);
}

Solution

  • As Daniel said, your class member must be an array of subscriptions to handle all of them.

    In addition to his responses, I would suggest to use the "async pipe" wherever you can, so the angular will do the unsubscribe by itself.