2017-07-12 180 views
3

一個服務同時在多個組件中調用。我們如何避免觸發多個API調用,並等待API完成並返回可觀察值。結合多個請求請求並在Angular 2中只敲擊一次

@Injectable() 
export class SomeService { 
    private data: string; 
    private _subject$: AsyncSubject<string[]> = new AsyncSubject<stirng[]>(); 
    private obs: Observable<any>; 
    constructor() { } 

public currentData$(): Observable<string[]> { 
    this.getData(); 
    return this._subject$.asObservable(); 
} 

private getData() { 
    this.http.get(this.url) 
    .map((r) => r)) 
    .share() 
    .subscribe((res) => { 
    this._subject$.next(res); 
    this._subject$.complete(); 
    }); 
} 

這裏currentData $()被多個組件同時調用。我如何避免多個API調用。

回答

2

這裏是你如何能做到這一點:

@Injectable() 
export class SomeService { 
    private data: string; 
    private _subject$: AsyncSubject<string[]>; 
    private obs: Observable<any>; 
    constructor() { } 

public currentData$(): Observable<string[]> { 
    if(!this._subject$) { 
     this._subject$ = new AsyncSubject<stirng[]>(); 
     this.getData().subscribe(this._subject$); 
    } 

    return this._subject$;  
} 

private getData() { 
    return this.http.get(this.url).map((r) => r)); 
} 
+0

非常感謝:) – user1853803

+0

@ user1853803,歡迎您 –

+0

你如何在你的自定義組件使用它? –