简体   繁体   English

Angular:如何正确执行Promise在使用routerLink导航之前完成?

[英]Angular: how to correctly enforce a promise to complete before navigation with routerLink?

New to angular development and need some insight on how to get async/await to work. 角度开发的新手,需要一些关于如何使异步/等待工作的见识。

I have a button that makes an API call and then loads the next page. 我有一个进行API调用然后加载下一页的按钮。 I need to wait to load the next page until the API call is complete. 我需要等待加载下一页,直到API调用完成。 Problem is it's not working. 问题是它不起作用。

HTML Button: HTML按钮:

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

nextPage() Function: nextPage()函数:

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

http functions: http函数:

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

This is because the click event handler bounded by the RouterLink directive is triggered before the promise completes. 这是因为在承诺完成之前触发了由RouterLink指令限制的click事件处理程序。 You will need to refactor your code in order to trigger the navigation manually: 您将需要重构代码以便手动触发导航

<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
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM