如何使用可观察数组修改对象?

时间:2018-04-02 04:33:13

标签: rxjs observable

我觉得这应该比我做的更简单!这是我目前所用的jsbin:http://jsbin.com/sasamaf/1/edit?js,console

我有表示“category”和“thing”的字符串数组。我最终想要创建一个Category项数组,每个项都有一个属性为Thing项的数组。每个Thing项都来自一个返回Observable的服务方法。

class ThingService {
    getThing(name: string): Rx.Observable<Thing> {
        var thing = new Thing();
        thing.name = name;
        thing.data = "data for " + name;
        return Rx.Observable.of(thing);
    } 
}

class Category {
    name: string;
    things: Thing[];
}

class Thing {
    name: string;
    data: string;
}

给定类别名称和事物名称的数组,如何创建一个返回填充了事物数组的Observable<Category[]>的函数?

category_names = [ "foo", "bar" ];
things_per_category = [ "Hello", "World" ];

这是我到目前为止所拥有的:

getCategories(): Rx.Observable<any> {
    return Rx.Observable.from(this.category_names
                .map(n => {
                    var category = new Category();
                    category.name = n;
                    return category;
                })
            )
            .flatMap(cat => {
                // For this category, create the array of things and
                // attach them to the "things" property of the category

                var ary_of_thing_observables = this.things_per_category.map(thing_name => {
                    console.log("getting thing " + thing_name + " for category " + cat.name)
                    return this.service.getThing(thing_name);
                })

                // ??? How to get from the Observable<Thing> to 
                // adding a Thing to the "things" array?

                return Rx.Observable.of("???");
            })         
    }
}

我最终希望返回的observable能够解决这个问题:

[
    { 
        name: 'Foo',
        things: [
            { name: 'Hello', data: 'data for Hello' },
            { name: 'World', data: 'data for World' }
        ]
    },
    { 
        name: 'Bar',
        things: [
            { name: 'Hello', data: 'data for Hello' },
            { name: 'World', data: 'data for World' }
        ]
    }
]

如何迭代我的数组,创建我的东西,并将它们附加到每个类别?

1 个答案:

答案 0 :(得分:1)

您可以使用forkJoinThing[]获取Observable<Thing>[],然后您可以使用mapThing[]值分配给该类别并返回类别本身。

要让组合的observable发出一个类别数组,你可以使用toArray

.flatMap(cat => {
  var ary_of_thing_observables = things_per_category.map(thing_name => {
    console.log("getting thing " + thing_name + " for category " + cat.name);
    return getThing(thing_name);
  });
  return Rx.Observable
    .forkJoin(ary_of_thing_observables)
    .map(things => {
      cat.things = things;
      return cat;
    });
})
.toArray();