Issue
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
The 2 subscriptions are asynchronous, and they start executing at the same time. There is no guarantee that the first one will complete before the other one, but you do have mechanisms at your disposal to make sure they execute in the order you want. For example, you could use the switchMap operator to perform the call to the API as soon as the id from your route parameters is available:
GetPostDetails() {
this.route.params
.pipe(
map((param) => param["id"]),
switchMap((id) => this.FeaturedPostDetail.GetFeaturedPost(id))
)
.subscribe((response) => {
this.featuredPost = response;
});
}
Answered By - Octavian Mărculescu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.