I’m going to get id parameter from URL and pass it to the service and then, get relevant information from API.
The component is:
export class ShowpostComponent implements OnInit {
featuredPost: FeaturedPost = {
id: 0,
postId: 0,
subject: '',
shortDiscription: '',
discription: '',
date: '',
reference: ''
}
constructor(
private FeaturedPostDetail:FeaturedPostService,
private route:ActivatedRoute
) { }
ngOnInit(): void {
this.GetPostDetails();
}
GetPostDetails(){
let Id: number;
this.route.params.subscribe(
param =>{
Id = param['id'],
console.log(Id);
}
);
this.FeaturedPostDetail.GetFeaturedPost(Id).subscribe(
response =>{
this.featuredPost = response;
}
)
}
}
My problem is that Id variable in this.FeaturedPostDetail.GetFeaturedPost(Id).subscribe gives error and says:
let Id: number Variable ‘Id’ is used before being assigned. ts(2454)
How can I fix it in my code?
>Solution :
All you need to do is give Id a default value, such as -1 or 0 like so:
GetPostDetails(){
let Id: number = -1;
Just another note on how the Id is set, because .subscribe is an observable type that is used to emit values over time, I would highly recommend to refactor GetPostDetails into following to make sure the correct value is returned and assigned in time:
GetPostDetails() {
this.route.params.subscribe(
param =>{
const Id = param['id'],
console.log(Id);
this.FeaturedPostDetail.GetFeaturedPost(Id).subscribe(
(response) => {
this.featuredPost = response;
})
}
);
}