我们是否需要取消订阅Angular中的http调用?

问题描述:

可能是一个愚蠢的问题,但无法轻松找到答案.

Probably a silly question, but couldn't find an answer easily.

在Angular应用程序中,我使用Rxjs进行http调用以获取数据并将数据发布到服务器.假设我有一个服务MyService,其方法如下:

In an Angular application where I'm using Rxjs to make http calls to get and post data to a server. Let's say I have a service MyService with a method like this:

getData() {
  this.http
      .get("mybackendurl/mydata")
      .map(res => res.json())
      .subscribe(data => this.data = data);
}

因此,假设我每次在页面上浏览时,都会在几个地方使用此方法. 不管这样做有多方便,我的问题是,这不像一个Promise,它会开始和结束,据我所知,它会保持连接打开直到源终止,所以我需要以某种方式取消订阅每次我完成请求时?

So, let's say I use this method in a couple places and a every time I navigate into a page. Regardless of the convenience of doing it this way, my question is, this is not like a Promise, that starts and finishes, as far as I know this keeps a connection open until the source terminates, so do I need to somehow unsubscribe from this every time I finish the request?

由于订阅是在服务中完成的,而不是在组件中完成的,因此该服务不会被破坏,因此我担心我可能会创建多个订阅和连接,而不是重用相同的订阅和连接.

As the subscription is done in a service and not in a component, the service won't be destroyed, hence I fear I might be creating multiple subscriptions and connections instead of reusing the same one.

谢谢!

对于Http请求,您无需取消订阅.它实际上是 完成 可观察的,所以您 没有任何内存泄漏 .

For Http request you don't need to unsubscribe. It actually completes the observable, so you will not have any memory leaks.

您可以使用Subscription对象的add功能进行检查.取消订阅时将调用此函数.您还可以通过将complete函数(第三个参数)传递到subscribe函数进行检查,该函数将在请求后调用,这意味着可观察性已完成.

You can check this by using add function of the Subscription object. This function is called when Subscription is unsubscribed. Also you can check via passing the complete function (the 3rd parameter) into the subscribe function, which will be called after the request and will mean that observable is completed.

this.http
    .get("mybackendurl/mydata")
    .map(res => res.json())
    .subscribe(data => this.data = data)
    .add(() => console.log('Unsubscribed'));