Angular 6 + RxJS 6.0 : How to push new element to array contained by Observable

前端 未结 2 1617
野趣味
野趣味 2021-02-15 15:52

I am receiving data from firebase server in chunks while rendering that data requires a library which insists on observable contains Array. I am somehow unable to push a new dat

2条回答
  •  野性不改
    2021-02-15 16:16

    Your subject here is an array of CalendarEvent, you have to pass an array of CalendarEvent in next() method. I would recommand to use a BehaviorSubject in your case. Here is a short example:

    import { Component } from '@angular/core';
    import { Observable, BehaviorSubject, of } from 'rxjs';
    import { take } from 'rxjs/operators';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      obsArray: BehaviorSubject = new BehaviorSubject([]);
      array$: Observable =  this.obsArray.asObservable();
    
      constructor() {
      }
    
      ngOnInit() {
        this.addElementToObservableArray('It works');
      }
    
      addElementToObservableArray(item) {
        this.array$.pipe(take(1)).subscribe(val => {
          console.log(val)
          const newArr = [...val, item];
          this.obsArray.next(newArr);
        })
      }
    }
    

    You can see a live example here: Stackblitz.

    Hope it helps!

提交回复
热议问题