Angular2: Unsubscribe from http observable in Service

北战南征 提交于 2019-11-27 12:46:51

问题


What is the best practice to unsubscribe within a Angular2 service from a http subscription?

Currently I do this but I'm not sure if this will be the best way.

import { Injectable } from "@angular/core";
import { Http } from "@angular/http";

import { Subject } from "rxjs/Subject";
import { ISubscription } from "rxjs/Subscription";

@Injectable()
export class SearchService {
    private _searchSource = new Subject<any>();

    public search$ = this._searchSource.asObservable();

    constructor(private _http: Http) {}

    public search(value: string) {
        let sub: ISubscription = this._http.get("/api/search?value=" + value)
            .map(response => <any>response.json())
            .do(data => this._searchSource.next(data))
            .finally(() => sub.unsubscribe()).subscribe();
    }

}

回答1:


A Service in Angular is a singleton. This means that the service will exist for the entire lifespan of your application.

The reason that you need to unsubscribe from an observable, is to avoid memory leaks. When do you get memory leaks? If something has been garbage collected while it was still subscribed to an observable, event listener, socket, ...

Since an Angular service never get's destroyed, unless your entire application get's destroyed, there is no real reason to unsubscribe from it. The observable will either complete or error or keep going as long as your application does.

Conclusion: Unsubscribing in a service is kind of pointless, since there is no chance of memory leaks.




回答2:


You don't need to unsubscribe from observable created by Http or HttpClient because it is finite observable (value will be emitted only once and complete will be called).

However, you CAN unsubscribe from the observable created by HttpClient to cancel the request. It mean you are no longer interested in data returned by the request.




回答3:


I disagree with KwintenP answer. Yes in case of observable to HttpClient call there is no need to unsubscribe as Vladimir mentioned correctly however in other observables you may definitely need to unsubscribe in a service.

Let see simple example: Assume we have a store that send observables and in the store we have a clicker observable that fire true whenever there is a click on the right mouse (for some weird reason) And assume we have MyWeirdService that do the following:

class MyWeirdService {
  doSomethingUnthinkableManyTimes() {
    this.store.select('clicker').subscribe(() => {
      console.log("Hey what do you know, I'm leaking");
    });
  }
}

this.store.select('clicker') returns an observable that we registering a new handler to it on every call to doSomethingUnthinkableManyTimes without cleaning it resulting in memory leak that will stay as long as the service is there (application lifetime in many cases)

Bottom line you don't need to unsubscribe in the case above of Http as Vladimir explained it well but in other cases you may need it.



来源:https://stackoverflow.com/questions/40861494/angular2-unsubscribe-from-http-observable-in-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!