Angular 2错误处理 - 发送到订阅组件

时间:2017-03-08 16:54:52

标签: javascript angular error-handling rxjs

我正在使用Angular 2 HTTP,并有一个订阅响应的组件。但是,当出现错误时,catch方法不会将错误返回给订阅的组件。它只是把它扔进控制台。

 saveFinalize(fcData: LastForecastInterface) {
    let responseData = JSON.stringify(fcData);
    let body = responseData;

    const headers = new Headers();
    headers.append('Content-Type', 'application/json;charset=UTF-8');

    return this.http.post('/saveFinalize', body, { headers: headers })
      .map((data: Response) => data.json())
      .catch(this.handleError);
}

public handleError(error: Response | any) {
    console.log('err: ', error)
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    // return Observable.throw(errMsg);
    return errMsg;
}

我订阅的组件没有得到回复

saveFinalize() {
  this.loadingData = true;
  return this.httpService.saveFinalize(this.getFc.fcData)
    .subscribe(response => {
        this.loadingData = false;
        console.log(response);
        let saveResponse = response.success ? 'Successfully Saved Finalized!' : 'Error Saving Finalized! - ' + response.message;
        let respType = response.success ? 'success' : 'danger';
        this.alertSvc.showAlert(saveResponse, respType);
    });
}

2 个答案:

答案 0 :(得分:10)

请在此处查看此代码:(来自https://angular.io/docs/ts/latest/guide/server-communication.html

getHeroes() {
  this.heroService.getHeroes()
                  .subscribe(
                    heroes => this.heroes = heroes,
                    error =>  this.errorMessage = <any>error);
}

请注意.subscribe()方法有2个参数。一个是您使用的响应,下一个是错误。为了将错误传递给订阅组件,您必须使用后面的参数,这将使您的代码如下所示:

  return this.httpService.saveFinalize(this.getFc.fcData).subscribe(response => {
    this.loadingData = false;
    console.log(response);
    let saveResponse = response.success ? 'Successfully Saved Finalized!' : 'Error Saving Finalized! - ' + response.message;
    let respType = response.success ? 'success' : 'danger';
    this.alertSvc.showAlert(saveResponse, respType);
  }, error => {
    // the errorMessage will be passed here in this "error" variable
  });

当订阅的方法返回成功的响应时,您只会得到您的回复。但是当订阅方法抛出错误时你不会得到你的响应,你只会得到错误(这是subscribe()方法的第二个参数)。

您还需要从handleError()方法中抛出错误。因此,不应仅返回字符串值(return errMsg;),而应使用return Observable.throw(errMsg);

答案 1 :(得分:0)

你可以做到

DomSanitizer

将为您返回响应。