加载数组时订阅事件发射器

Subscribe to event emitter when array is loaded

我有以下代码:

this.itemsService.getItems()
    .subscribe(i => this.items = i);

但是,用户可以 select 一种类型的项目,所以我有一个事件发射器:

this.typeofitems.selectedType.subscribe(type => this.type = type);

并且运行良好。

现在我想用 filter function 过滤项目列表 this.items。问题是,我不知道项目加载何时完成,尽管如果我在订阅中添加日志:

this.itemsService.getItems()
    .subscribe(i => {this.items = i; console.log("completed");});

这表明我已经完成了。所以我尝试了:

this.itemsService.getItems()
    .subscribe(i => {
        this.items = i;
        this.typeofitems.selectedType.subscribe(type => {
            this.type = type;
            this.filterByType();
        });
    });

filterByType() {
    this.itemsfilteredByType = this.items.filter(i => i.type === this.type)
}

但它不起作用。所以我想我不能在订阅者里面订阅。 我怎样才能实现它?

请注意,您在 filter() 回调中使用的是 = 而不是 ==,因此请确保这不是问题所在。

无论如何,您可以使用运算符 combineLatest(),每次它的任何来源发出一个值时都会发出一个值(同时必须从每个来源发出至少一个值):

function getItems() {
  return Observable.of([{type: 1, val: 345}, {type: 2, val: 107}, {type: 1, val: 926}, {type: 2, val: 456} ]);
}

let typeOfItems = new Subject();

Observable.combineLatest(getItems(), typeOfItems)
  .subscribe(vals => {
    let [items, typeOfItem] = vals;

    let results = items.filter(i => i.type == typeOfItem);
    console.log(results);
  });

typeOfItems.next(2);

这按 type == 2 过滤项目并打印到控制台:

[[object Object] {
  type: 2,
  val: 107
}, [object Object] {
  type: 2,
  val: 456
}]

多亏了 combineLatest() 它的工作原理首先接收所有项目,然后我告诉它使用 typeOfItems.next(2); 通过 type == 2 过滤它们,这会触发对 [=15= 的回调的调用] 使用 Array.filter() 实际过滤和打印过滤的项目(注意这是 Array.fitler() 而不是 Observable.filter())。

观看现场演示:https://jsbin.com/nenosiy/5/edit?js,console

顺便说一句,您当然可以 subscribe() 在另一个 subscribe() 回调中。请记住,您必须手动取消订阅之前的订阅。

看到一个非常相似的问题: