Angular2:取消订阅可在服务中观察到的http [英] Angular2: Unsubscribe from http observable in Service

查看:114
本文介绍了Angular2:取消订阅可在服务中观察到的http的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular2服务中取消http订阅的最佳实践是什么?

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

}

推荐答案

Angular中的服务是单例.这意味着该服务将在您的应用程序的整个生命周期中存在.

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, ...

由于Angular服务永远不会被销毁,除非整个应用程序都被销毁,否则没有真正的理由取消订阅.可观察对象将完成或出错,或者与您的应用程序一样持续运行.

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.

这篇关于Angular2:取消订阅可在服务中观察到的http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆