2017-03-22 68 views
0

我在我的數據庫中有5000個日誌條目,並且在我只加載50的時候,我有一個「加載更多」按鈕,然後應該加載51-100,101-150即分批在50個記錄中。如何追加項目到一個Observable

正如我讀這不能通過Observable完成。所以我嘗試使用問題,我有INFACT解決了這個問題,但我不知道這是否是正確的方式,因爲我在RxJS很新,並感謝您的指導

這裏是我的組件:

export class ControllerLogComponent implements OnInit { 

    @Input() controller: Controller; 
    logEntries: Log[] = []; 
    loadMoreCount: BehaviorSubject<number> = new BehaviorSubject<number>(0); 
    allLogEntries: Subject<Log[]> = new Subject<Log[]>(); 
    skip: number = 0; 
    max: number = 50; //temp 

    constructor(private translate: TranslateService, private controllerService: ControllerService, private _toast: NotificationsService) { } 

    ngOnInit() { 
     this.controllerService.getLog(this.controller.remoteID, this.skip, this.max).subscribe(a => { 
      this.logEntries = this.logEntries.concat(a); 
      this.allLogEntries.next(this.logEntries); 
      this.loadMoreCount.next(a.length);    
     }); 
    } 

    public loadMore() { 
     this.skip += this.max; 
     this.controllerService.getLog(this.controller.remoteID, this.skip, this.max).subscribe(a => { 
      this.logEntries = this.logEntries.concat(a); 
      this.loadMoreCount.next(a.length); 
      this.allLogEntries.next(this.logEntries); 
     }); 
    } 

     private handleError(error: any) { 
     console.log("error: " + error); 

    } 

} 

這裏是在主題爲使用循環我的組件的HTML:

<tbody *ngIf="allLogEntries"> 
      <tr *ngFor="let log of allLogEntries | async"> 
       <td> 
        <i class="fa fa-toggle-off" aria-hidden="true" *ngIf="log.type==0"></i> 
        <i class="fa fa-toggle-on" aria-hidden="true" *ngIf="log.type==1"></i> 
        <i class="fa fa-info-circle" aria-hidden="true" *ngIf="log.type==2"></i> 
        <i class="fa fa-info-circle" aria-hidden="true" *ngIf="log.type==3"></i> 
        <i class="fa fa-exclamation-circle" aria-hidden="true" *ngIf="log.type>3"></i> 

       </td> 
       <td>{{ log.logged | date:'medium' }}</td> 
       <td>{{ log.logentry }}</td> 
      </tr> 
     </tbody> 
+0

是不是很不必要的複雜使用主題時,你可以迭代'this.logEntries',你要追加的結果? – martin

+0

但這是一個簡單的數組。當數組內的項目發生變化時,如何反映在視圖中?不需要像Observable/Subject這樣的東西。 –

回答

2

爲了保存某種狀態的觀察到流裏面,你可以使用scan()。例如:

Rx.Observable 
 
    .fromEvent(document.getElementById('more'), 'click') 
 
    .map(() => [1,2,3]) 
 
    .scan((list, items) => list.concat(items), []) 
 
    .subscribe(x => console.log(x));
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script> 
 
<button id="more">load more</button>

相關問題