未捕获(承诺):状态响应:401未经授权的URL

时间:2017-04-29 14:56:59

标签: angular typescript observable router canactivate

enter image description here我正在尝试为路由器实施authGuard。但是当我干扰错误代码时,应用程序实际上会中断。我不知道如何解决它。需要帮助。

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

我的身份验证服务

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

}

我收到此错误,未捕获(在承诺中):状态响应:401未经授权的URL。

ScreenShot of my Error

当我收到该错误时,我的页面全部空白。

2 个答案:

答案 0 :(得分:3)

我通过返回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);
      });

答案 1 :(得分:1)

你需要使用一个catch,catch必须返回一个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()
}