Uncaught (in promise): Response with status: 401 Unauthorized for URL

Sibiraj picture Sibiraj · Apr 29, 2017 · Viewed 7.4k times · Source

enter image description hereI am trying to implement authGuard for my Routers. but when I interfere with error codes, the app breaks actually. I don't know how to tackle it. assistance needed.

My AuthGuard

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

    return this._auth.validate()
      .map((isValidated) => {
        if (isValidated && localStorage.getItem('authToken') && this.checkCookie()) {
          return true;
        }
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
        return false;
      });
  }

My Auth Service

@Injectable()
export class AuthService {

  loginStatus;

  constructor(private http: Http, private _apiEndPoint: ApiEndPoint, private router: Router) { }

  validate() {

    return this.http.get(this._apiEndPoint.validate)
      .map(
      (response: Response) => {

        const result = response.json();

        // check authentication status from response
        if (result.authenticated) {
          return true;
        } else {
          return false;
        }
      })
    .catch(error => Observable.throw(error));
  }

}

I am getting this error, Uncaught (in promise): Response with status: 401 Unauthorised for URL.

ScreenShot of my Error

and when I get that error my page goes all blank.

Answer

Sibiraj picture Sibiraj · May 1, 2017

I fixed by returning observable of false

return this._auth.validate()
      .map((isValidated) => {
        if (isValidated && localStorage.getItem('authToken') && this.checkCookie()) {
          return true;
        }
      }).catch(() => {
        this.router.navigate(['/login']);
        return Observable.of(false);
      });