将元素添加到Angular2 +中的rxjs BehaviorSubject或数组的Subject [英] Add elements to rxjs BehaviorSubject or Subject of an array in Angular2+

查看:90
本文介绍了将元素添加到Angular2 +中的rxjs BehaviorSubject或数组的Subject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从我看到了这个示例如何处理他们试图在其组件之间共享的字符串,但是我的数据类型稍微复杂一些:

I see how this example works for the string they are trying to share across their components, but my data type is a little more complex:

就是说,我认为我的BehaviorSubject应该看起来像这样:

Namely, I think my BehaviorSubject should look like this:

private currentPopulationSource: BehaviorSubject<Population> = new BehaviorSubject<Population>(new Population(new Array<Organism>()));

我的人口模型只是一系列生物的容器:

My population model is simply a container for an array of Organisms:

import { Organism } from './organism.model';

export class Population {
  private individuals: any;
  constructor(individuals: Organism[]){
     this.individuals = individuals;
  }

  getIndividuals(){
    return this.individuals;
  }
}

我有一个生物实例,我们称其为organic1.

I have an instance of Organism, let's call it organism1.

我想将其添加到人口"模型中包装的个人数组中,并且我希望多个不相关的组件订阅人口BehaviorSubject"(我目前有 private currentPopulation = this.currentPopulationSource.asObservable(); 在我的currentPopulationSource声明之后,在我的PopulationManager服务中,如我在本教程中看到的那样.

I'd like to add it to the individuals array wrapped in the Population model, and I'd like for multiple unrelated components to subscribe to the population BehaviorSubject (I currently have private currentPopulation = this.currentPopulationSource.asObservable(); in my PopulationManagerService right after my declaration of currentPopulationSource, as I saw in the tutorial).

我不清楚向我的currentPopulationSource添加生物体1的语法是什么( .next()在这里似乎没有意义).

It's unclear to me what the syntax would be to add organism1 to my currentPopulationSource (.next() doesn't seem to make sense here).

如果我想要一个不断增长的数组作为发出的东西,也许BehaviorSubject不是在这里做出的最合适的选择吗?如果有更好的选择(ReplaySubject?),我不太知道如何实现.

Perhaps BehaviorSubject isn't the most appropriate choice to make here if I want an ever-growing array to be the thing emitted? If there is a better option (ReplaySubject?), I don't quite know how to implement it.

我的人口经理服务:

import { Injectable } from '@angular/core';
import { Organism } from './organism.model';
import { Population } from './population.model';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PopulationManagerService {
  private currentPopulationSource: BehaviorSubject<Population> = new BehaviorSubject<Population>(new Population(new Array<Organism>()));
  currentPopulation = this.currentPopulationSource.asObservable();
  constructor() { }

  addOrganismToPopulation(organism: Organism){
    this.currentPopulationSource.next(new Population(new Array<Organism>(organism))); //This does not work
    // this.currentPopulation.getIndividuals().push(organism); //This did not work either, because currentPopulation is of type Observable<Population> rather than of type Population
  }
}

在我的组件中:

let testIndividual: Organism = this.individualGenService.makeIndividual("green", "blue");
    this.popManager.addOrganismToPopulation(testIndividual);
    this.popManager.currentPopulation.subscribe(results =>{
      console.log(results.getIndividuals()); //returns undefined
    });

当前返回未定义.

非常感谢您提供有关此问题的帮助.

Very grateful for any help with this issue.

推荐答案

如果我正确理解,您想在种群对象内部的生物列表中添加一个新生物.这是在使用行为主题时.

If I understand correctly, you want to add a new organism to the list of organisms that is inside a population object. This while using a behavior subject.

在您的示例中,您可以执行以下操作.

In your example you could do the following.

addOrganismToPopulation(organism: Organism){
    this.currentPopulationSource
        .pipe(take(1))
        .subscribe((population: Population) => {
            this.currentPopulationSource.next(
                new Population([...population.getIndividuals(), organism]))
            )
        });
  }

那么我们在这里做什么.为了将新生物添加到当前种群中,我们需要了解生物列表.因此,我们赞成拥有人口的可观察物.在订阅中,我们创建了一个新的人口实例.在创建新实例时,我们将与新生物一起创建一系列已知生物.然后,我们将新的/更新的种群添加到流中.

So what are we doing here. To add a new organism to the current population we need to know the list of organisms. So we subscribe to the observable that holds the population. Inside the subscription we create a new instance of population. While creating the new instance we create an array of the already known organisms together with the new one. Then we next the new/updated population onto the stream.

请注意,我只采用流的一个值,即 take(1).这是因为当我们要计算新的生物列表时,我们仅需要当前种群.这也可以防止不必要的内存泄漏. take 运算符在一个事件过去后立即从流中取消订阅.

Notice that I only take one value of the stream, take(1). This is because the moment we want to calculate the new list of organisms we only need the current population. This as well prevents an unwanted memory leak. The take operator unsubscribes from the stream the moment one event has passed.

对于行为案例而言,对于您的用例而言,行为主题是否是一个不错的选择,很难用最少的信息来说明.

Whether the behavior subject is a good choice for your use case is hard to say with a minimum of information.

这篇关于将元素添加到Angular2 +中的rxjs BehaviorSubject或数组的Subject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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