In my component A, there is an async method abc(). Within this method, I await another async method xyz() from service X. This xyz() method contains additional await calls (which need to be executed sequentially and use the response for subsequent requests). In certain scenarios where specific calls return negative results, I want to redirect the user to one of two pages (for now, let's assume it's just one page). I am currently using router.navigate(['/error'])
, but the redirection is not functioning as intended. I expect it to halt further code execution and immediately redirect the user.
x.service.ts
async ngOnInit() {
await this.abc();
}
async abc(): Promise<any> {
await this.serviceX.xyz();
// The following calls still proceed even if the navigation line in the xyz() method is accessed
await this.service3.magicMethod();
await this.service4.anotherMethod();
}
a.component.ts
async xyz(): Promise<any> {
const result = await this.service1.getData();
if (result !== 'OK') {
this.router.navigate(['/error']);
}
const userAnswer = await this.service2.userSelection();
if (userAnswer !== 'OK') {
this.router.navigate(['/error']);
}
}
Both service1 and service2 consist of async functions where HTTP responses are awaited using toPromise()
. For example:
async getData(): Promise<SomeResponse> { // or userSelection()
const response = await this.wrapperService.getHttpResponse().toPromise();
console.log(response);
return response as SomeResponse;
}