Angular 6 + RxJS 6.0:如何将新元素推送到Observable包含的数组 [英] Angular 6 + RxJS 6.0 : How to push new element to array contained by Observable

查看:48
本文介绍了Angular 6 + RxJS 6.0:如何将新元素推送到Observable包含的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Firebase服务器分块接收数据,同时渲染该数据需要一个坚持可观察包含数组的库.我以某种方式无法将新的数据块推送到可观察的包含的现有数据块阵列中,

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,

在dataservice中,我正在按主题的下一个呼叫,并尝试添加新的calEvent

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>>>;

和ngOnInit,我正在向其提供数据

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:我正在使用 lib来呈现日历,并使用remoteDB来呈现事件.

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

谢谢

推荐答案

您的主题是一个CalendarEvent数组,您必须在next()方法中传递一个CalendarEvent数组.我建议您在情况下使用BehaviorSubject.这是一个简短的示例:

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);
    })
  }
}

您可以在此处看到一个实时示例: Stackblitz .

You can see a live example here: Stackblitz.

希望有帮助!

这篇关于Angular 6 + RxJS 6.0:如何将新元素推送到Observable包含的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆