簡體   English   中英

在 Angular2 服務中多次發出 Http 請求

[英]Http request made multiple times in Angular2 service

我創建了一個發出簡單 GET 請求的服務:

private accountObservable = null;

constructor(private _http: Http) {
}

getAccount () {
    // If we have account cached, use it instead
    if (this.accountObservable === null) {
        this.accountObservable = this._http.get('http://localhost/api/account')
            .map(res => <Account> res.json().data)
            .catch(this.handleError);
    }

    return this.accountObservable;
}

我在引導函數中添加了該服務以在全局范圍內提供它(我希望為所有組件提供相同的實例):

provide(AccountService, { useClass: AccountService })

問題是當我在不同的組件中調用此服務時,每次都會發出 GET 請求。 因此,如果我將它添加到 3 個組件中,即使我檢查了 observable 是否已經存在,也會發出 3 個 GET 請求。

ngOnInit() {
  this._accountService.getAccount().subscribe(
    account => this.account = account,
    error =>  this.errorMessage = <any>error
  );
}

如何防止多次發出 GET 請求?

使用Observable.share()

if (this.accountObservable === null) {
    this.accountObservable = this._http.get('./data/data.json')
      .share()
      .map(res => res.json())
      .catch(this.handleError);
}

普朗克

在 Plunker 中,AppComponent 和 Component2 都調用了getAccount().subscribe()兩次。

使用share() ,Chrome 開發者工具的“網絡”選項卡會顯示一個對data.json HTTP 請求。 注釋掉share()后,有 4 個請求。

有兩種類型的可觀察對象。

Cold Observable:每個訂閱者接收所有事件(從一開始)

Hot observable :每個訂閱者接收訂閱后發出的事件。

Cold Observables 是默認的。 這就是多次觸發 WS 調用的原因。

要使 Observable Hot,您必須使用以下 Rx 的運算符鏈:

.publish().refCount()

在你的情況下:

getAccount () {

    let accountObservable = this._http.get('http://localhost/api/account')
            .map(res => <Account> res.json().data)
            .catch(this.handleError);

    return accountObservable.publish().refCount();
}

就我而言,這是因為表單發布和按鈕點擊設置為相同的偵聽器

更新的解決方案是:

1) 更改您的 getAccount() 方法以使用share

getAccount () {
    // If we have account cached, use it instead
    if (this.accountObservable === null) {
        this.accountObservable = this._http.get('http://localhost/api/account')
            .pipe(share())
            .map(res => <Account> res.json().data)
            .catch(this.handleError);
    }

    return this.accountObservable;
}

2) 添加import { share } from 'rxjs/operators'; .ts文件的頂部以消除share上的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM