Check if the user logged in on any page change in Angular 2

后端 未结 4 1081
Happy的楠姐
Happy的楠姐 2020-12-15 00:00

Slowly but surely progressing with Angular2. And now I faced the following challenge. I want to check if the user logged in or not on every page change (in other words on lo

4条回答
  •  执笔经年
    2020-12-15 00:24

    If you use routing (and it seems to be the case since you say: "on every page change"), you can leverage several things:

    • Create a custom router-outlet (a sub class of RouterOutlet) that checks authentication with its activate method is called. In this case, you can have something global. Something like that:

      @Directive({
        selector: 'auth-outlet'
      })
      export class AuthOutlet extends RouterOutlet {
        (...)
      
        activate(oldInstruction: ComponentInstruction) {
          var url = this.parentRouter.lastNavigationAttempt;
          if (isAuthenticated()) {
            return super.activate(oldInstruction);
          } else {
            (...)
          }
        }
      }
      

      See this question for more details:

      • Angular 2 Authentication with child routes
    • Leverage the CanActivate decorator to check is a component can be activated or not. In your case, you can execute authentication checking at this level.

    • Something could also be done at the RouterLink level to show / hide route links. In this case, you can apply roles on these links based on related route configuration and current user hints. See this question for more details:

      • Angular2. How to hide(no-render) the link in the menu after check access?

    This can be also handled within an HTTP interceptor (a class that extends the Http one). In this case, when a request is executing, you can plug some authentication checks:

    @Injectable()
    export class CustomHttp extends Http {
      constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
      }
    
      request(url: string | Request, options?: RequestOptionsArgs): Observable {
        console.log('request...');
        if (isAuthenticated()) {
          return super.request(url, options).catch(res => {
            // do something
          });        
        } else {
          // Redirect to login page
          // Or throw an exception: return Observable.throw(new Error(...));
        }
      }
    
      (...)
    }
    

    See this question for more details:

    • How to create interceptors in Angular2?

提交回复
热议问题