0

I want to pass the current URL from the app.routing.ts file to the guard because there is a problem where the url gets reset in the guard for some reason. Below I added how I pass the data to the route.

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

Now my question is: how can I get this URL data in my guard with angular 7.3? I've tried multiple solutions like the ActiveRoute solutions below

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

or

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

but both don't seem to work for me sadly

EDIT: I'm trying to get this data in the canActivate function of my custom guard

EDIT 2.0: I tried the solution below but the log in the .then() doesnt even get triggered before the app redirects to the root route

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;
  });
}
Djkobus
  • 131
  • 1
  • 2
  • 8

1 Answers1

0

In your Component where you are trying to get the params: (I just updated my answer)

constructor(router:Router, route:ActivatedRoute) {
    router.events
      .filter(e => e instanceof NavigationEnd)
      .forEach(e => {
        console.log(route.root.firstChild.snapshot.data['url']);
    });
}
Rebai Ahmed
  • 1,509
  • 1
  • 14
  • 21
  • Tried this approach too but it also didnt work sadly – Djkobus Jan 10 '20 at 12:25
  • I updated my question with trying this solution. this would work if i was trying to get the data in a component but since i want to use it in a guard i can't. The canActivate function gets triggered before the constructor and i tried multiple things with promises etc. to get the data but i still cant seem to get the data before the app redirects to the root url. – Djkobus Jan 11 '20 at 15:08