2017-03-22 86 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>

相关问题