2017-06-01 102 views
0

我試圖在點擊加載更多後更新Observable數組,但會導致多次調用API。如何在加載時更新可觀察數組更多

這裏是我的html:

<app-productlistother *ngFor="let item of favs$ | async" [item]="item"></app-productlistother> 

<a (click)="loadMore()">Load More</a> 

組件:

ngOnInit() { 
    this.favs$ = this._favoriteService.getFavorites(this.pageNum); 
    } 

    private loadMore() { 
    this.pageNum = this.pageNum + 1; 

    this.favs$ = this.favs$.merge(this._favoriteService.getFavorites(this.pageNum)); 
    } 

和服務:

getFavorites(page): Observable<Response> { 
    return this._http.get(environment.baseUrl + 'favorite?page=' + page) 
     .map((result: Response) => result.json().data); 
    } 

我怎樣才能解決這個問題?在每個新的請求getFavorites(page)我需要在陣列的底部推新結果...

+0

您需要在您的服務中使用observable,並且需要訂閱組件中的obeservable,並且一旦加載更多的數據就會被觸發,數據將被添加到observable中,並且組件將會列出所有更改,然後自行更新 –

+0

您能給我舉個例子嗎? – Vladimir

+0

@Vladmir舉了一個例子,希望它有幫助 –

回答

0
@Injectable() 
export class MyBooleanService { 
    myBool$: Observable<any>; 

    private boolSubject: Subject<any>; 

    constructor() { 
     this.boolSubject = new Subject<any>(); 
     this.myBool$ = this.boolSubject.asObservable(); 
    } 

    ...some code that emits new values using this.boolSubject... 
} 

然後在你的組件,你會有這樣的事情:

@Component({...}) 
export class MyComponent { 
    currentBool: any; 

    constructor(service: MyBooleanService) { 
     service.myBool$.subscribe((newBool: any) => { this.currentBool = newBool; }); 
    } 
} 

現在取決於你需要什麼要做到這一點,你可能需要在你的組件中進行更新,但這是使用可觀察的要點

另一種選擇是在模板中使用異步管道,而不是顯式訂閱構造函數。同樣,這取決於你需要用bool值做什麼。

+0

我不需要訂閱Observable異步管道爲我做我只需要添加新的可觀察到當前。 – Vladimir

+0

我沒有得到你 –

+0

我沒有在我的代碼中使用訂閱,異步管道爲我做...我需要在加載更多的功能合併2觀察到1 – Vladimir

0

所以你有沒有HTML和<app-productionother>模板只是{{item.name}}?在這種情況下,爲什麼不構建這樣的:

<ng-template *ngFor="let item of favs$ | async"> 
    <app-productlistother [item]="item"></app-productlistother> 
</ng-template> 

這保持異步管關閉的重複元件,以便不被關於項目的每個迭代重複異步管。我想這就是爲什麼它被稱爲多次(可能與你有物品相同的數字)。

此外,如果merge沒有解決問題,請嘗試concatConcat將等待,直到第一個可觀測數據完成發射,然後將加入第二個可觀測數據。合併不等待第一個觀察結束。我想如果你點擊加載更多,並且沒有與第二批交互的初始數據等,你會希望按順序加載數據。