Issue
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?
Solution
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();
}
}
}
Answered By - eta32carinae
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.