代码之家  ›  专栏  ›  技术社区  ›  ste9206

rxjs可观察合并无法按预期工作

  •  1
  • ste9206  · 技术社区  · 7 年前

    我需要为post请求生成此结果:

    {
    "names": [
        {
            "id": "t3xcb9xAyX",
            "username": "Gennaro"
        },
        {
            "id": "Csdu65RKon",
            "username": "Marco"
        },
        ...
    ],
    "createdAt":"04/07/2018 - 11.49.51"
    }
    

    所以我使用rxjs完成了这项工作:我创建了两个observate(一个用于names,一个用于created at)并在最后合并:

    const notObj = utils.getNotificationType(codeProduct, Parse);
    const csvObj = utils.getNotificationType(codeProduct, Parse);
    
    const query = new Parse.Query(notObj);
    const dateQuery = new Parse.Query(csvObj).descending('createdAt');
    
    
    const names = from(query.find())
        .map(el => el.map((e) => {
            return {
                id: e.id,
                username: e.get('username')
            }
        }))
        .mergeMap((arr) => Observable.of({
            names: arr
        }));
    
    const lastUpdate = from(dateQuery.first())
        .map(res => moment(res.createdAt).format('DD/MM/YYYY - HH:mm:ss'))
        .map(res => {
            return {
                createdAt: res
            }
        });
    
    
    merge(names, lastUpdate)
        .subscribe(
            (data) => res.send(serialize(data)),
            (error) => res.send(serialize(error)),
            () => console.log('complete')
        );
    

    问题是最终合并只检索我 "names" .我可以用另一个结果 .zip() 运算符,但我有一个json数组而不是一个对象。

    我的问题是:为什么 merge() 不合并两个结果而只合并第一个结果吗?谢谢你

    1 回复  |  直到 7 年前
        1
  •  4
  •   martin    7 年前

    那不是什么 merge 做。它合并可观察的流而不是对象本身。使用 forkJoin 相反,它将发出一个结果数组,然后自己将其与 map 以下内容:

    const names$ = ...;
    const lastUpdate$ = ...;
    
    forkJoin(names$, lastUpdate$)
      .map(([ names, lastUpdate ]) => ({ names, lastUpdate }))
      .subscribe(...)