如何在Angular中执行Subscription任务后触发函数调用

时间:2017-07-09 16:10:07

标签: angular rxjs

我正在开发一个Angular 4应用程序,它具有一个允许用户上传图像的服务。我希望只要上传成功,我的组件就会得到通知。怎么做的?

举个例子,这是我的函数,它在我的service.ts文件中返回一个Subscription对象:

uploadImage(new_image:File) {
  this.uploading = true;
  let url = '/products/photo/';
  let newImagePayload = new FormData();

  newImagePayload.append('photo', new_image, new_image.name);

  return this.queryService.postQueryFormData(url, newImagePayload)
    .subscribe(result => {
      this.uploading = false;
      this.image_location = result['photo'];
    });
}

在我的组件中,此函数被称为:

let my_subscription = this.cardService.uploadImage(newImage)
   \\ I want to call this.randomfunction() whenever my uploading is finished.

这是怎么做到的?我希望我可以做如下的事情:

my_subscription.subscribe()

但显然不允许这样做。

1 个答案:

答案 0 :(得分:3)

您无法使用subscribe,因为您正在通过调用Subscription方法收到uploadImage。我建议您在组件中调用subscribe方法,然后返回Observable。您可以使用do运算符来调用您想要的操作并返回Observable。代码看起来像这样:

uploadImage(new_image: File) {
    this.uploading = true;
    let url = '/products/photo/';
    let newImagePayload = new FormData();

    newImagePayload.append('photo', new_image, new_image.name);

    return this.queryService.postQueryFormData(url, newImagePayload).do(result => {
        this.uploading = false;
        this.image_location = result['photo'];
    });
}

然后在组件内部,您可以调用subscribe方法。