Sibiraj
Sibiraj

Reputation: 4756

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

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.

Upvotes: 2

Views: 9205

Answers (2)

Sibiraj
Sibiraj

Reputation: 4756

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);
      });

Upvotes: 4

Aadi Droid
Aadi Droid

Reputation: 1739

you need to use a catch, and catch has to return an observable.

validate() {

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

    const result = response.json();

    // check authentication status from response
    return result.authenticated;
  })
  .catch(error => Observable.throw(error)); // If you want to throw nothing, then return Observable.empty()
}

Upvotes: 1

Related Questions