【问题标题】:Angular 4 - Catching the err object from Service To ComponentAngular 4 - 从服务到组件捕获错误对象
【发布时间】:2017-12-24 20:31:14
【问题描述】:

我正在使用 angular 作为前端和 spring-security 作为后端的登录页面,一切似乎都工作正常,但是当我尝试通过从服务捕获错误来处理异常时组件不工作。

service.ts

 login(form) {
      var objectToSend = 'j_username=' + form.j_username + '&j_password=' + form.j_password;
      const headers = new Headers(
        {
          'Content-Type': 'application/x-www-form-urlencoded',
        }
      );
      const options = new RequestOptions({headers: headers, withCredentials: true});
      return this.http.post('http://localhost:8080/***********/authenticate', objectToSend, options)
        .map((res) => res)
        .catch((error: any) => {
          if (error.status === 401) {
            console.log(error.status + ' is the current status');
            return Observable.throw(new Error(error.status));
          } else if (error.status === 400) {
            return Observable.throw(new Error(error.status));
          } else if (error.status === 409) {
            return Observable.throw(new Error(error.status));
          } else if (error.status === 406) {
            return Observable.throw(new Error(error.status));
          }
        });
    }

login.component.ts

     loginProcess() {
      this._authenticationService.login(this.form.value).subscribe(
        res => {
          this.data = res;
          if (res.status === 200) {
            this._authenticationService.getRoles().subscribe(
              resp => {
                if (resp.status === 200) {
                  this.roles = JSON.parse(resp.text());
                  this.role = this.roles[0].authority;
                  localStorage.setItem('role', this.role);
                  this.connectedUser.eusLogin = this.form.value.j_username;
                  this.saveConnectedUser(this.connectedUser);
                  this.updateSessionTimeOut();
                  if (this.role === 'ROLE_ADMIN') {
                    this._router.navigate(['home']);
                  }
                } else {
                  this.showErrorMsgDetail = true;
                  this.error = true;
                }
              },
              error => {
                this.error = true;
              }
            );
          } else {
          }
        },
        err => {
          if (err.status === 401) {
            this.showErrorMsgDetail = true;
            this.errorMsgDetail = 'Bad credentials, try again';
          }
        }
      );
    }

问题在于捕获从服务到组件的响应代码,在组件级别 err.status 未定义。

希望你们能解决这个问题。

【问题讨论】:

  • 你能多展示一点组件代码吗?

标签: javascript spring angular error-handling


【解决方案1】:

您正在尝试在没有任何 Event Emitter 或 BehaviorSubject 的情况下进行通信,您希望如何在其他地方捕获错误?

您必须在服务中捕获您的错误,在构造函数中将其注入您的登录组件,然后您只需使用 this.myService.getDataFromWebService(post) 从您的组件调用您的服务。

getDataFromWebService(postData: Kpi): EventEmitter<Kpi> {
    const event: EventEmitter<Kpi> = new EventEmitter();
    this.sendPost(myService.API_PATH, postData).subscribe((data) => {
      try {
        if (this.checkError(data)) {
          const parseData: Kpi = Kpi.parse(data);
          event.emit(parseData);
        } else {
          event.emit(new Kpi());
        }
      } catch (ex) {
        this.env.error("Unknown error", "Invalid data received");
        console.log("Exception", ex);
        kpiEvent.emit(new Kpi());
      }
    });
    return event;
  }

【讨论】:

    猜你喜欢
    • 2022-11-16
    • 2017-03-08
    • 2018-02-11
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多