Angular 2 : Redirect to a page at application startup

爷,独闯天下 提交于 2019-12-12 03:28:25

问题


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!


回答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/




回答2:


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.



来源:https://stackoverflow.com/questions/36698454/angular-2-redirect-to-a-page-at-application-startup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!