angular 2嵌套订阅,http.post未被调用

时间:2017-02-08 08:55:27

标签: angular rxjs

我正在尝试在进行http post post之前压缩图像

 this.activityService.addCourse(
      course,
      fileToUpload
    ).subscribe(
      (result) => {
          console.log(result);
          this.handleSuccess('course_added_successfully');
      },
      error => {
        this.handleError("an_error_occured");
      }
    );

在activityService.addCourse中:

return this.imageService.compressImage(fileToUpload).map(result => {
      if (fileToUpload)    {
        fileToUpload = result;
        input.append("file", fileToUpload);
        input.append("filetype_id", String(0));
      }
      if (typeof result.name !== 'undefined' && typeof result.size !== 'undefined' && typeof result.type !== 'undefined') {
        this.http.post(Constants.URL_ADD_COURSE, input)
          .map(FunctionsService.extractData).catch(FunctionsService.handleError);
      }
      else {
        Observable.throw('Error compressing image');
      }
});

调试时,我可以看到呼叫到达this.http.post(Constants.URL_ADD_COURSE, input)并且返回的值成功,但是没有进行呼叫(在Ins Inspect元素中>网络我可以看到没有发生任何事情)

1 个答案:

答案 0 :(得分:1)

我注意到你从未订阅过this.http.post observable。这是一种冷酷的观察,意味着在有人订阅它之前它实际上不会做任何事情。如果你真的不关心调用本身的结果,你也可以调用.publish(),将其转换为热的可观察对象。

编辑: 一种选择是调用switchMap而不是map。这样,您可以确保在继续其余处理之前完成了http请求。

return this.imageService.compressImage(fileToUpload).switchMap(result => {
  if (fileToUpload)    {
    fileToUpload = result;
    input.append("file", fileToUpload);
    input.append("filetype_id", String(0));
  }
  if (typeof result.name !== 'undefined' && typeof result.size !== 'undefined' && typeof result.type !== 'undefined') {
    return this.http.post(Constants.URL_ADD_COURSE, input)
      .map(FunctionsService.extractData).catch(FunctionsService.handleError);
  }
  else {
    return Observable.throw('Error compressing image');
  }
});

如果你真的想要对待是一个不重要的“边叫”而忽略了你可以使用的结果

this.http.post(Constants.URL_ADD_COURSE, input)
 .map(FunctionsService.extractData)
 .catch(FunctionsService.handleError)
 .publish();
相关问题