首页 文章

处理UI中的授权错误

提问于
浏览
0

我已经尝试在我的Angular中实现授权数小时了:example . 我已经构建了一个HTTP拦截器来捕获错误,但我不确定如何在登录视图中显示它 . 我've tried to pass a variable around but I can' t让它工作

这些是我的AuthService的一些方法:

login(email: string, password: string) {
    this.logout();

    return this.http
        .post("http://localhost:3000/user/login", {
            email,
            password
        })
        .do(res => {
            this.setSession(res);
        })
        .shareReplay();
}

    private setSession(authResult) {
    const expiresAt = moment().add(authResult.data.expiresIn, "second");

    localStorage.setItem("id_token", authResult.data.idToken);
    localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf()));
}

这是我的Http Inceptor:

@Injectable()导出类AuthInterceptor实现HttpInterceptor {

constructor(private router: Router, private _data: AuthdataService) { }


intercept(req: HttpRequest<any>,
    next: HttpHandler): Observable<HttpEvent<any>> {

    const idToken = localStorage.getItem("id_token");

    if (idToken) {
        const cloned = req.clone({
            headers: req.headers.set("Authorization",
                "Bearer " + idToken)
        });

        return next.handle(cloned);
    }
    else {
        return next.handle(req).do(
            succ => console.log(succ),
            err => {
                if (err.status === 401) {
                    console.error('AUTHENTICATION FAILED');
                    this.router.navigateByUrl('/login');
                    //HOW CAN I SEND THIS TO THE UI?
                }
            }

        );
    }
}
}

最后我的登录组件:

loginUser() {
if (this.loginForm.valid) {
  const email = this.loginForm.value.email;
  const password = this.loginForm.value.password;

  //set loading to true and then false if error
  this.loading = false;
  this._data.login(email, password).subscribe(() => {
    if (this._data.isLoggedIn()) {
      this.router.navigateByUrl("/");
    } else {
      //never reaches here
    }
  });
}
}

我尝试从我的服务调用isLoggedIn(),它检查localstorage中的令牌,但是如果dataservce抛出401错误,则不会执行else语句,因为该方法不会被执行 .

总结:如何向我的登录HTML组件显示“不正确的电子邮件或密码”这样的消息?

谢谢你的帮助 .

1 回答

  • 1

    您可以从拦截器中抛出错误并在登录组件中捕获它 .

    它应该是这样的:

    return Observable.throw(err);
    

    在登录组件中捕获它:

    this._data.login(email, password).subscribe(() => {
       if (this._data.isLoggedIn()) {
          this.router.navigateByUrl("/");
       } else {
          //never reaches here
       }
    }, err => {
       /* Write your logic here*/
    });
    

相关问题