问题描述
可能是一个愚蠢的问题,但无法轻松找到答案.
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 请求,您不需要取消订阅.它实际上完成 observable,因此您将没有任何内存泄漏.
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
函数来检查,该函数将在请求后调用,这意味着 observable 已完成.>
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'));
这篇关于我们需要取消订阅 Angular 中的 http 调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!