0

我想将 app.routing.ts 文件中的当前 URL 传递给守卫,因为由于某种原因导致 url 在守卫中被重置存在问题。下面我添加了如何将数据传递给路由。

const appRoutes: Routes = [
  {
    path: '',
    loadChildren: './plain-page.module#PlainPageModule',
    canActivate: [TravelplanTokenGuard],
    data: {'url': new URL(window.location.href)}
  },

现在我的问题是:如何使用 Angular 7.3 在我的守卫中获取此 URL 数据?我尝试了多种解决方案,例如下面的ActiveRoute解决方案

canActivate() {
  this.route.data.subscribe(data => {
    console.log(data);
  });
}

或者

const url = this.route.snapshot.data['url']

但可悲的是,两者似乎都不适合我

编辑:我正在尝试在我的自定义警卫的canActivate 函数中获取这些数据

编辑 2.0:我尝试了下面的解决方案,但在应用程序重定向到根路由之前,.then() 中的日志甚至没有被触发

canActivate() {
  return new Promise((resolve) => {
    this.router.events.subscribe(event => {
      console.log(event)
      if (event instanceof NavigationEnd) {
        this.url = this.route.root.firstChild.snapshot.data['url'];
        resolve();
      }
    });
  }).then(() => {
    console.log('in de tokenguard', this.token)
    if (!this.jwtHelper.isTokenExpired(this.token)) {
      return true;
    }
    return false;
  });
}
4

1 回答 1

0

在您尝试获取参数的组件中:(我刚刚更新了我的答案)

constructor(router:Router, route:ActivatedRoute) {
    router.events
      .filter(e => e instanceof NavigationEnd)
      .forEach(e => {
        console.log(route.root.firstChild.snapshot.data['url']);
    });
}
于 2020-01-08T12:56:33.770 回答