Reputation: 31
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!
Upvotes: 0
Views: 2785
Reputation: 657506
There are two common ways
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/
Upvotes: 1
Reputation: 15270
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.
Upvotes: 0