Search code examples
angularinterceptorunauthorized

unwanted error 401 caoused by ErrorINterceptor


I have a problem with a stackblitz that relates to authentication, login and user registration. The problem is that when I try to access the HomePage, having not yet logged in, 'ErrorInterceptor' intercepts the error 401 and as per the code it sends me back to the login. I don't want this behavior, I would like to browse in the HomePage even if I don't log in. The only page to have restricted access is RestrictedPage which has a guard in the route declaration. If I comment on line 16 of the file 'routing.module.ts and decompress the line 17 the guard is disabled and I am allowed to access RestrictedPage even without having logged in but I cannot access the HomePage anyway. Basically I can't find the code that prevents me from accessing the HomePage when I haven't logged in. This is the stackblitz. Thanks! https://stackblitz.com/edit/authenticationdemo?file=src%2Fapp%2Frouting.module.ts


Solution

  • You are getting routed to login because of this line (22) in the error-interceptor.ts

    this.router.navigate(['/login']);
    

    If you are wondering when this line of code is executed, it is when you call the loadAllUsers() function in the ngOnInit of home.component.ts.

    You are trying to load all the users but you are not authenticated. Interceptor catches this and redirects you to your login page.

    If you (for the time being) remove the call to loadAllUsers() on ngOnInit, then you will stay in the home component.

    There is nothing wrong with your guard. You have your guard working as expected :)