【问题标题】:Angular: how to correctly enforce a promise to complete before navigation with routerLink?Angular:如何在使用 routerLink 导航之前正确执行完成承诺?
【发布时间】:2019-12-16 05:33:56
【问题描述】:

Angular 开发新手,需要了解如何让 async/await 工作。

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

HTML 按钮:

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

nextPage() 函数:

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]="['../Review']" 在触发点击事件时立即触发路由更改。承诺解决后,您必须使用Router 服务更改路线。所以更新nextPage() 调用then() 并在之后执行路由更改。
  • @churill 当然,在 PUT api 调用完成之前加载下一页。该页面正在执行 http GET 请求以供用户查看。所以他们正在审查旧数据,因为它在 PUT 完成之前加载了页面

标签: angular promise async-await angular-router


【解决方案1】:

这是因为由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
   }
}

【讨论】:

  • 简洁而正确的答案。非常感谢,这是一个巨大的帮助。我以为问题是异步而不是路由器链接。已接受答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
  • 2015-07-18
  • 1970-01-01
  • 2018-05-12
  • 2019-11-26
  • 1970-01-01
  • 2019-11-26
相关资源
最近更新 更多