0

I'm facing a little issue for my web application in Angular 2.

Each application launch, I would check if the user has a right of access. However I don't know how to redirect the user to the route which makes this process whatever the place where he is.

Any ideas?

Thanks in advance!

Gen
  • 31
  • 1
  • 5

2 Answers2

1

There are two common ways

  • use CanActivate
  • use a custom RouterOutlet

    where you check if the user is authenticated otherwise redirect to the login route

See also
- Check if the user logged in on any page change in Angular 2
- http://www.captaincodeman.com/2016/03/31/angular2-route-security/

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • it seems that angular does not handle redirections easily .. Many efforts just to force the first page of my application... I will try these two methods, thanks ! – Gen Apr 19 '16 at 10:57
0

You could implement OnInit interface and add redirection/check in ngOnInit method and add @CanActivate to your child components:

class Static{
   static authenticated:boolean = false;
   static initialized:boolean = false;
}

@CanActivate(()=>{
   if(Static.authenticated && Static.initialized){
      return true;
   }
   return false;
})

protected ngOnInit():any
{
    this.loginFacade.refresh().subscribe(event=>
    {
        var url = event.success ? this.location.path() : Routes.LOGIN;

        Static.authenticated = event.success;

        this.router.recognize(url).then(()=>
        {
            return Promise.resolve(url);
        }, (e)=>
        {
            return Promise.resolve(Routes.LOGIN);
        }).then((url)=>
        {
            Static.initialized = true;
            return this.router.navigateByUrl(url);
        });
    });
}

also remove default route.

kemsky
  • 14,727
  • 3
  • 32
  • 51
  • OnInit is called but I can't use the router in my main class... I have error "cannot read property 'constructor' of undefined". Thanks for your answer – Gen Apr 19 '16 at 10:51
  • I tried your solution in my class App which is called by Bootstrap..And it seems that we can't make redirects in this class – Gen Apr 19 '16 at 11:00