角度:在使用routerLink导航之前,如何正确执行要完成的承诺?



刚接触 angular 开发,需要一些关于如何让 async/await 工作的见解。

我有一个按钮,可以进行 API 调用,然后加载下一页。 我需要等待加载下一页,直到 API 调用完成。 问题是它不起作用。

网页按钮:

<button type="button" [routerLink]="['../Review']" (click)=nextPage()">Next</button>

下一页(( 函数:

private async nextPage(){ 
await this.practiceData.put_Practice(this.practice.practiceId,this.practice).toPromise();
});
}
}

http 函数:

put_Practice(practiceId: number, practice: Practice)
{
return this.httpClient.put(this.baseUrl + '/Practice/' + practiceId, practice, this.httpOptions);
}

这是因为在承诺完成之前触发了由RouterLink指令限定的 click 事件处理程序。 您需要重构代码才能手动触发导航

<button type="button" (click)=nextPage()">Next</button>
import {Router,ActivatedRoute} from '@angular/router';
export class MyComponent {
constructor(private readonly router: Router, private readonly route: ActivatedRoute){}
async nextPage(){
await this.practiceData.put_Practice(this.practice.practiceId,this.practice).toPromise();
await this.router.navigate(["../Review"],{relativeTo: this.route});
// or without async/await you can simply chain the promises
}
}

最新更新