auth0-blog / angular2-authentication-sample

This is a sample that shows how to add authentication to an Angular 2 (ng2) app
MIT License
966 stars 334 forks source link

Better way to redirect #54

Open mrpotato3 opened 8 years ago

mrpotato3 commented 8 years ago

Hi!

after many test I think this is the best way to redirect in LoggedInOutlet.ts.

activate(ci:ComponentInstruction)
{
  let url = this.parentRouter.lastNavigationAttempt;
  let route;

  if (!this.publicRoutes[url] && !localStorage.getItem('jwt'))  // !isAuth + !publicRoute -> Redirect to login
    route = ['Login'];
  else if (this.publicRoutes[url] && localStorage.getItem('jwt'))  // isAuth + publicRoute -> Redirect to dashboard
    route = ['Main'];
  else  // Continue routing without changes
  {
    this.parentRouter.navigateByUrl(url);
    return super.activate(ci);
  }

  this.parentRouter.navigate(route);
  return super.activate(this.parentRouter.generate(route).component);
}

This avoids to show other parts of the web.

I hope this helps.

dmastag commented 8 years ago

This is a great suggestion, but at my attempt the url have now an additional "/" in front of them so I had to add that to the publicRoutes. But this fixed a Bug that I had on my instance.

Thanks @mrpotato3