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

ahr*_*ins 3 javascript error-handling rxjs angular

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

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

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);
    });
}
Run Code Online (Sandbox Code Playgroud)

sam*_*vin 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);
}
Run Code Online (Sandbox Code Playgroud)

请注意.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
  });
Run Code Online (Sandbox Code Playgroud)

当订阅方法返回成功响应时,您将只获得响应.但是当订阅方法抛出错误时您将无法获得响应,您将只获得错误(这是subscribe()方法的第二个参数).

您还需要从handleError()方法中抛出错误.所以不应该只返回字符串value(return errMsg;),而应该使用return Observable.throw(errMsg);.