我的订阅不处理错误

时间:2017-03-10 18:42:22

标签: angular angular2-services angular2-components angular2-observables

我订阅了一项服务,我从外部API请求图片网址并将其存储在共享服务中。

逻辑:
1.清空当前图像阵列
2.从API请求图像,并将其推送到(新清除的)数组(response =>)
3.如果URL返回错误,请使用默认(占位符)图像填充数组(错误=>)

出于某种原因,尽管存在错误,但错误仍未得到处理。 我已经发布了我的组件和错误消息以供上下文使用。

Component.ts

  getImages(vehicleID: number, color: string): void {
    this._carConfigService.car.colors.exterior.urls = [];
    this._FAPIService.getImagesForColors(vehicleID, color)
      .subscribe(
        response => {
        response.products[0].productFormats.forEach(pF => {
        this._carConfigService.car.colors.exterior.urls.push(pF.assets[0].url);
        });
      },
        error => {
          this.errorMessage = <any>error;
          if (this._carConfigService.car.colors.exterior.urls.length === 0) {
            this._carConfigService.car.colors.exterior.urls = this._carConfigService.defaultImages;
          }
      });
  }

我收到以下错误:

Failed to load resource: the server responded with a status of 422 ()
EXCEPTION: Response with status: 0  for URL: null
Uncaught Response

1 个答案:

答案 0 :(得分:1)

您需要使用常规方法处理异常处理

export class TaskService {
    private _url = "api/products/datanew.json";
    constructor(private _http: Http) {
    }
    getTasks(): Observable<any[]> {
        return this._http.get(this._url)
            .map((response: Response) => <any[]>response.json())
            .do(data => console.log("data we got is " + JSON.stringify(data)))
            .catch(this.handleError);

    }
    private handleError(error: Response) {
            console.log(error);
            return Observable.throw(error.json().error || 'Internal Server error');
    }
}

另外,我有一个问题。

  1. 您正在获取数据但是您没有分配任何对象?没有返回类型