In my project, I am utilizing Angular 10. Within the ngOnInit function, I have nested HTTP calls structured like this:
ngOnInit(): void {
let communetyid;
this.route.data.subscribe(data => {
this.route.params.subscribe(params => {
if(data.category === "code")
{
this.dataService.getCode(params.code)
.subscribe(resp => { communetyid = resp.results.communityId });
}
else
{
communetyid = params.id
}
this.dataService.getCommunityById(communetyid)
.subscribe(response => { this.community = response.results;
///other http calls
})
})
})
})
The issue arises where dataService.getCommunityById
is executed before the value of communetyid is set due to asynchronous operations, resulting in an error message in the console.
Is there a way to modify the code so that when dataService.getCommunityById
is called, the value of communetyid is initialized?
I understand that one approach would be to include dataService.getCommunityById
within the subscribe method of dataService.getCode
, but I am looking for a solution that avoids duplicating code.