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

怎甘沉沦 提交于 2020-01-12 07:28:08

问题


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 data chunk to existing data chunk array contained by observable,

From dataservice I am calling by subject's next and trying to add a new calEvent

 this.homeWorkerService.eventSubject.next(calEvent);

In component, I have following code

events$: Observable<Array<CalendarEvent<any>>>;

and ngOnInit, I am supplying data to it like

this.events$ = this.service.eventSubject.asObservable();

Could you please suggest any way by which I can add a new event to observable which already hold my events.

PS : I am using this lib to render calendar and using remoteDB to render events.

Thanks,


回答1:


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<any[]> = new BehaviorSubject<any[]>([]);
  array$: Observable<any> =  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!




回答2:


In addition to GeoAstronaute's answer, here's how I would remove stuff from the array:

  removeElementToObservableArray(idx) {
    this.array$.pipe(take(1)).subscribe(val => {
      const arr = this.subject.getValue()
      arr.splice(idx, 1)
      this.subject.next(arr)
    })
  }

I.E: your ngforloop in the HTML could have the let i = index, which would provide an index to the data you wanted to remove. Secondly, the remove function has to be inside the ngforloop tag :-)



来源:https://stackoverflow.com/questions/50856647/angular-6-rxjs-6-0-how-to-push-new-element-to-array-contained-by-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!