我有组件A,它具有异步方法abc()。在此方法内部,我在service X中等待另一个async method xyz()。在此xyz()方法中,我还有另一个await调用(我需要按顺序执行调用,并在下一个请求中使用响应)。可能发生的情况是,在两个特定的调用中结果为否,我想将用户重定向到两个页面之一(当前,我们假设那只是一页)。我正在使用router.navigate(['/error'])
,但是它不起作用...我希望它将停止代码的进一步执行,并将立即执行重定向。
x.service.ts
async ngOnInit() {
await this.abc();
}
async abc(): Promise<any> {
await this.serviceX.xyz();
// other calls with await keyword are still executed even if in xyz() redirect should occurs
}
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']);
}
}
service1和service2都具有异步功能,正在等待使用toPromise()
的HTTP响应。像这样的东西:
async getData(): Promise<SomeResponse> { // or userSelection()
const response = await this.wrapperService.getHttpResponse().toPromise();
console.log(response);
return response as SomeResponse;
}
[我知道该应用程序能够导航到两个页面,因为我通过在abc()
中引发错误,在ngOnInit中捕获该错误并使用this.router.navigate(['/error']);
重定向用户来对其进行了检查。
[如果您希望处理停止,那么您需要告诉它停止。除非另有说明,否则调用函数router.navigate
将继续处理。
async xyz(): Promise<any> {
const result = await this.service1.getData(); //
if (result !== 'OK') {
this.router.navigate(['/error']);
return;
}
const userAnswer = await this.service2.userSelection();
if (userAnswer !== 'OK') {
this.router.navigate(['/error']);
return;
}
}
我在调用return;
之后添加了router.navigate
语句。
很显然,最后一个return;
是多余的。您的代码所隐含的含义是,如果第二次调用成功,则将发生其他事情。