I'm using Subscription to get a parameter from the route in angular. Here is the code:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription} from 'rxjs';
@Component({
selector: 'farm-house',
templateUrl: './house.component.html',
styleUrls: ['./house.component.scss']
})
export class GreenhouseComponent implements OnInit, OnDestroy {
private routeSub: Subscription;
id: string;
constructor(private route: ActivatedRoute) {
this.id = "";
}
ngOnInit(): void {
this.routeSub = this.route.params.subscribe(params => {
this.id = params['id'];
});
}
ngOnDestroy() {
this.routeSub.unsubscribe();
}
}
But the problem is that the compiler says:
Property 'routeSub' has no initializer and is not definitely assigned in the constructor.
My question is, what is the best way to initialize a Subscription object?
Most of the cases it's should be enough to check the subscription before unsubscribe.
ngOnDestroy() {
if(this.routeSub) {
this.routeSub.unsubscribe();
}
}
In your case, it's not required to initialize subscription because you already called subscribe method in ngOnInit(). Error might come because you are calling unsubscribe() directly on Subscription without checking it's initialized or not.
I've come up with another solution which is using Subscription.EMPTY from this question.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription} from 'rxjs';
@Component({
selector: 'farm-house',
templateUrl: './house.component.html',
styleUrls: ['./house.component.scss']
})
export class GreenhouseComponent implements OnInit, OnDestroy {
private routeSub: Subscription;
id: string;
constructor(private route: ActivatedRoute) {
this.routeSub = Subscription.EMPTY;
this.id = "";
}
ngOnInit(): void {
this.routeSub = this.route.params.subscribe(params => {
this.id = params['id'];
});
}
ngOnDestroy(): void {
if(this.routeSub) {
this.routeSub.unsubscribe();
}
}
}