Angular 2 Cancelling Route Navigation on UnAuthenticate

前端 未结 3 1983
星月不相逢
星月不相逢 2021-01-16 09:27

I have an app, with 3 links: Home (/), Sign in (/user/sign-in) and User Detail (/user).

When user click Home, my app will be show content public

When user cl

3条回答
  •  逝去的感伤
    2021-01-16 10:08

    For this I'll implement authService concept and before accessing any protected route, I'll check whether user is authenticated or not.If user is not authenticated I'll redirect him to login page.There if you want cancel button too, the you can put cancel button in LOGIN Component and when you press it you can redirect user back to previous component by using CanActive hook in Login Component). Just try to learn this and if you want any further help i'm here.

    auth.ts

    import {Observable} from 'rxjs/Observable';
    
    export class Auth {
      constructor() {
        this.loggedIn = false;
      }
    
      login() {
        this.loggedIn = true;
      }
    
      logout() {
        this.loggedIn = false;
      }
    
      check() {
        return Observable.of(this.loggedIn);
      }
    }
    

    For further code check out,

  • this plunker which is nicely written for protected routes
  • This implementation will surely help you for your use-case.

提交回复
热议问题