Angular:如何在使用 routerLink 导航之前正确执行完成承诺?
Angular: how to correctly enforce a promise to complete before navigation with routerLink?
angular 开发新手,需要了解如何让 async/await 工作。
我有一个按钮可以调用 API 然后加载下一页。我需要等到 API 调用完成后才能加载下一页。问题是它不工作。
HTML 按钮:
<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);
}
这是因为在 promise 完成之前触发了 RouterLink
指令限定的点击事件处理程序。
您将需要重构代码以手动触发 导航:
<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
}
}
angular 开发新手,需要了解如何让 async/await 工作。
我有一个按钮可以调用 API 然后加载下一页。我需要等到 API 调用完成后才能加载下一页。问题是它不工作。
HTML 按钮:
<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);
}
这是因为在 promise 完成之前触发了 RouterLink
指令限定的点击事件处理程序。
您将需要重构代码以手动触发 导航:
<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
}
}