[英]Angular Observable being called multiple times
我有一個服務,其中定義了一個全局可觀察對象,如下所示:
@Injectable()
export class XYZService {
country: Observable<any>;
isBrowser: boolean;
constructor(private http: Http,
private httpClient: HttpClient,
private router: Router,
@Inject(PLATFORM_ID) private platformId: any) {
this.isBrowser = isPlatformBrowser(platformId);
if(this.isBrowser && !this.country) {
this.country = this.http.get('https://ipinfo.io')
.map(res => res.json())
.catch(() => {
return Observable.of({'country': 'SG'});
});
};
}
getLocation(): Observable<any> {
return this.country;
}
現在在我的幾個組件中,我像這樣在構造函數或ngOnInit中調用getLocation函數:
this.XYZService.getLocation()
.subscribe(res => {
this.country = res['country'];
});
我的期望是對ipinfo.io的請求只會被發送一次。 但是,這沒有發生。 從網絡日志中,我可以看到多次向ipinfo發出請求。 看起來是一些計時問題。 如果在構造函數中添加調試器或console.log語句,則僅調用一次。 但是,發送了多個請求。
您可以使用rxjs 共享運算符。 這將確保后續的訂戶共享相同的可觀察序列(直到觀察者的數量返回0為止)
this.country = this.http.get('https://ipinfo.io')
.map(res => res.json())
.catch(() => {
return Observable.of({'country': 'SG'});
})
.share();
您也可以使用shareReplay運算符。 不同之處在於,將來將為所有訂戶存儲可觀察的結果。 例如,說您在應用程序加載時訂閱了可觀察對象,而在10分鍾后訂閱時使用了shareReplay
,則可觀察對象將返回相同的結果,而不會發出另一個http請求。 而使用share
,觀察者的數量在初始http請求完成后返回到0。 將來的訂閱將觸發另一個http請求
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.