【问题标题】:Perform http request before switching to next route在切换到下一个路由之前执行 http 请求
【发布时间】:2020-10-19 09:08:01
【问题描述】:

我想在离开页面导航到任何其他路线时执行发布请求。

我尝试过使用:

  this.subscriptionGrade = router.events
      .pipe(filter((event) => event instanceof NavigationStart))
      .pipe(
        concatMap(() => {
          return this.submitScore();
        })
      )
      .subscribe((res) => {
        this.snackBar.openSnackBar("Score submitted", "");
      });


  submitScore() {
    const score = { score: this.scoreForm.get("score").value };
    if (this.scoreForm.get("score").value) {
      return this.learningContentService.gradeAssignment(
        this.selectedAttempt,
        score
      );
    } else {
      return of(null);
    }
  }

这会执行 http 重新请求,但会在从 http 请求收到响应并且请求被取消之前切换到下一个路由。

【问题讨论】:

    标签: angular angular8 angular-routing angular-router


    【解决方案1】:

    可以在这条路由上使用canDeactivate,检查http调用是否成功

    export interface CanComponentDeactivate {
     canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
    }
    
    ...
    
    @Injectable()
    class CanDeactivateComponent implements CanDeactivate<CanComponentDeactivate>{
     constructor() {}
     canDeactivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
     let data= route.data.data;
     return this.service.post(url, data)
       .pipe(
         map(response => response.status === 'success'),
         catchError(error => of(false))
       );
     }
    }
    

    你的路线

    {
     path: 'yourRoute',
     component: Component,
     canActivate: [CanDeactivateComponent ],
     data: { data: {...}}
    }
    

    【讨论】:

    • 如果是 post 请求呢?
    • 同样的事情,post 或 get 不会改变任何东西
    • 我在关注您发布的苏格兰威士忌链接
    • 是的,这是一个简单的例子,我已经更新了我的答案以获取数据
    • 我给出了相同的代码并在我想要检查的组件内部编写了一个方法 canDeactivate 并在路由中提供保护..我收到错误无效 canActivate 保护..
    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多