【发布时间】:2017-04-13 04:33:47
【问题描述】:
在 Angular2 服务中取消订阅 http 订阅的最佳做法是什么?
目前我这样做,但我不确定这是否是最好的方法。
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();
}
}
【问题讨论】:
-
在 observable 完成时取消订阅似乎是多余且毫无意义的。
-
@günter-zöchbauer 好吧,我的问题不是我的问题,我的问题是:最佳实践是什么。那么?
-
我认为对于没有意义的事情没有最佳实践:D 也许只是 - 不要这样做。
-
我不应该做什么? @günter-zöchbauer 也许一个解释会比无用的 cmets 更好
标签: angular rxjs5 unsubscribe