【问题标题】:get response before navigating to next route在导航到下一条路线之前获得响应
【发布时间】:2020-05-13 14:32:19
【问题描述】:

当我导航到新路线时,我想将一些数据发布到 api。我还希望在获得 api 调用的响应后加载下一条路由。

我的路由器事件订阅:

     this.subscriptionGrade = router.events
      .pipe(filter((event) => event instanceof NavigationStart))
      .subscribe((event) => {
        this.submitScore();
      });

我正在取消订阅 ngOnDestroy:

     ngOnDestroy(): void {
        this.subscriptionGrade.unsubscribe();
      }

提交评分功能:

      submitScore() {
        const score = { score: this.scoreForm.get("score").value };
        if (this.scoreForm.get("score").value) {
          this.learningContentService
            .gradeAssignment(this.selectedAttempt, score)
            .subscribe((res) => {});
        }
      }

现在我可以在路线更改时提交分数,但在我从提交分数 api 获得响应之前,它会导航到新路线。我只想在响应后路由到下一页,因为我想要下一页中的更新数据。如何实施?请注意,用户可以导航到他选择的任何路线。

【问题讨论】:

    标签: angular rxjs angular8


    【解决方案1】:

    您需要使用守卫canActivatecanDeactivate,第一个在应该加载新路线时使用,第二个在要离开路线时使用。

    https://angular.io/api/router/CanActivate

    https://angular.io/api/router/CanDeactivate

    @Injectable()
    export class LoadGuard implements CanActivate {
        constructor(protected readonly http: HttpClient) {}
    
        public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
            return this.http.get('MY_URL').pipe(
              tap(response => {
                // do something with response
              }),
    
              // allowing route
              mapTo(true),
    
              // in case if response not 200 we don't allow to load the route.
              catchError(() => of(false)),
    
            );
        }
    }
    

    canDeactivate 也一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      相关资源
      最近更新 更多