Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

angular - Angular2: Unsubscribe from http observable in Service

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();
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...