【问题标题】:Angular error message from service pass to component从服务传递到组件的角度错误消息
【发布时间】:2020-04-08 07:32:35
【问题描述】:

我想请教如何设法让我的错误响应从后端显示在前端。对于后端,我使用的是 Spring boot 2,对于前端,我使用的是 Angular 8。所以在我尝试登录时,如果用户没有提供正确的凭据,那么用户会收到一条错误消息,但在我的情况下我正在使用一项服务,当用户在提供电子邮件和密码后单击登录时发出请求。我在控制台中收到错误消息,但它来自我的服务而不是来自组件,我想问我如何将它传递给零件。 例如,我提供了错误的电子邮件或密码,当我单击登录时,我收到带有以下错误消息的 HttpErrorResponse “错误:{成功:错误,消息:“无效的电子邮件或密码!”}”这很好,但我在我的服务中得到了它,如何将此错误传递给登录组件。 (我知道我用 sessionStorage 试过很愚蠢...)

auth.service.ts

 auth({email, password}, callback){
    const helper = new JwtHelperService();

    this.http.post('//localhost:8080/login',{email, password})
            .subscribe(userData => {
              localStorage.setItem('username', email);
              let tokenStr = 'Bearer ' + userData['accessToken'];
              localStorage.setItem('token', tokenStr);

              const tkn = localStorage.getItem('token');
              const decodedToken = helper.decodeToken(tkn);

              localStorage.setItem('currentUserId', decodedToken['sub']);
              console.log(decodedToken['sub']);

              return callback && callback(userData);
            },(err: HttpErrorResponse) => {
              console.log(err);
            });
}

login.component.ts

 login() {
    this.authService.auth(this.user, (e) => {

      let resp: any;
      resp = e.accessToken;

      if (resp != null) {
        // store user details  in local storage to keep user logged in between page refreshes
        this.accountService.loadProfile()
            .subscribe(user => {
              localStorage.setItem('currentUser', JSON.stringify(user));
              this.router.navigateByUrl('/profile');
            }, (err:HttpErrorResponse) => {
              console.log(err.error);
            })
      }
    });
  }

【问题讨论】:

    标签: java angular typescript spring-boot


    【解决方案1】:

    不要订阅 auth.service 而是返回一个 observable 以便它可以在其他地方订阅。进行以下更改:

     auth({email, password}, callback){
        const helper = new JwtHelperService();
        return this.http.post('//localhost:8080/login',{email, password});             
     }
    

    改为订阅login.component.ts

    login() {
    
        ...
    
        this.authService.auth(...).subscribe(() => {
           // code when it is successful
        }, (err:HttpErrorResponse) => {
           console.log(err.error.message);
        }
    }
    

    【讨论】:

    • 非常感谢您的帮助!非常感谢。
    猜你喜欢
    • 2018-07-08
    • 2018-10-26
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多