2017-03-06 48 views
2

我試圖從多個組件的以下服務共享一個http請求的結果。我遇到的問題是,每個組件對getMe()函數的請求都會創建一個新的http調用。 MeService服務僅在頁面的根模塊中聲明爲提供者,並在每個* .component.ts中導入,所以這不是由多次重新聲明服務作爲提供者的(常見)錯誤導致的子組件。從輸出中可以看出,這很可能是由於調用的異步性質造成的,但如果我錯了,請糾正我的錯誤。緩解Angular2服務中的多個http請求

這裏是服務代碼:

import { Injectable } from '@angular/core'; 
import { Headers, Http } from '@angular/http'; 

import 'rxjs/add/operator/toPromise'; 

@Injectable() 
export class MeService { 

    private apiUrl = 'api/get/me'; 

    private me: Object; 

    constructor(private http: Http) { } 

    getMe(): Promise<Object> { 

     console.log("OBSERVATION 1: " + this.me); 

     if (this.me) { 

      //Not sure if this is correct or not, I've never reached this block yet 
      return Promise.resolve(this.me) 

     } else { 

      return this.http.get(this.apiUrl) 
       .toPromise() 
       .then(response => { 

        console.log("OBSERVATION 2: " + this.me); 

        this.me = response.json(); 

        console.log("OBSERVATION 3: " + this.me); 

        return this.me 
       }) 
       .catch(this.handleError); 

     } 
    } 

    //Not relevant, just for completeness 
    private handleError(error: any): Promise<any> { 

     console.error('An error occurred', error); // for demo purposes only 
     return Promise.reject(error.message || error); 

    } 
} 

在控制檯的輸出。請注意,[object Object]中填充了正確的數據,爲了清晰起見,我已經檢查過並省略了JSON.Stringify()。

觀察1:未定義

觀察1:未定義

觀察2:未定義

觀察3:[對象的對象]

觀察2:[對象的對象]

觀察3:[對象對象]

我相信發生的事情是,在任何http調用返回之前加載Angular組件,導致引導時出現多個請求。什麼纔是減輕這一點的正確和最好的方法?

回答

2

嘗試返回請求本身並在組件中執行操作。你必須使用承諾嗎? Angular傾向於觀察者。

return this.http.get(this.apiUrl).map(res => res.json()); 

然後在您的每個組件中訂閱。

+0

將此標記爲正確答案,因爲它將我引導至此工作實現:[http://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-的-AN-角度-2-HTTP-網絡叩](http://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an -angular-2-HTTP-網絡呼入/ 36291681#36291681) –

0

感謝來自chrispy的提示,我傾向於Observables,它似乎確實是實現異步http調用的首選方式。但是,僅從組件內訂閱並不會阻止從服務到API的多次調用,直到找到this answer,我纔得到它的工作。我不確定這是否是最佳做法,但它有效。