【问题标题】:RxJS: BehaviorSubject and groupBy operatorRxJS:BehaviorSubject 和 groupBy 运算符
【发布时间】:2018-08-01 04:31:32
【问题描述】:

Here 它说:

// RxJS v6+
import { from } from 'rxjs';
import { groupBy, mergeMap, toArray } from 'rxjs/operators';

const people = [
  { name: 'Sue', age: 25 },
  { name: 'Joe', age: 30 },
  { name: 'Frank', age: 25 },
  { name: 'Sarah', age: 35 }
];
//emit each person
const source = from(people);
//group by age
const example = source.pipe(
  groupBy(person => person.age),
  // return each item in group as array
  mergeMap(group => group.pipe(toArray()))
);
/*
  output:
  [{age: 25, name: "Sue"},{age: 25, name: "Frank"}]
  [{age: 30, name: "Joe"}]
  [{age: 35, name: "Sarah"}]
*/
const subscribe = example.subscribe(val => console.log(val));

在我的代码中,我没有使用 'from' 运算符创建可观察对象,而是使用 BehaviorSubject.asObservable() 方法。

Person { name: string, age: number }

    private _all: BehaviorSubject<Person[]>;
    all: Observable<Person[]>;

    constructor() {
        this._all = new BehaviorSubject<Person[]>([]);
        this.all = this._all.asObservable();
    }

我可以使用异步管道遍历“全部”。但是当我尝试使用 groupBy 运算符时,我得到了数组本身,而不是一个一个地包含人员作为流:

this.all.pipe(
    groupBy(
        item => ...   <-- here 'item' is Person[], not a Person
    )
);

我做错了什么?

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    简单的答案是(不幸的是)这是不可能的。这是另一个 post 涉及类似问题。

    你可以在两者之间做一个步骤来达到想要的目标:

    选项 1: 无需订阅

    // directly access the BehaviorSubject's value
    const list = from(this._all.value);
    this.list.pipe(
        groupBy(
            item => ...  
        )
    );
    

    选项 2: 订阅,因为它是 Observable

    // catch the plain list inside the subscription
    this.all.subscribe(result => {
        const list = from(result);
        this.list.pipe(
            groupBy(
                item => ... 
            )
        );
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      • 2020-01-25
      相关资源
      最近更新 更多