【问题标题】:Sync nested subscribes in angular 5以角度 5 同步嵌套订阅
【发布时间】:2018-04-06 17:12:01
【问题描述】:

我有一个类似的功能:

function(param: any): Subject<any> {

    let newsubj: Subject<any> = new Subject<any>();
    let thing;

    this.dataContextService.dataContext.getFullThing({ param: param }).subscribe(result => {
        if (result) {

            thing = result.thing;

            this.dataContextService.dataContext.Table.Query(query => query
                .orderBy(["ID desc"])
                .top(1)
            ).subscribe(number => {
                if (number) {

                    let increment = number + 1;

                    let newObject = new Object({ id: increment, thing: thing });
                    this.dataContextService.dataContext.Favorite.Post(newObject).subscribe(result => {
                        newsubj.next(newObject);
                        newsubj.complete();
                    })

                }

            })
        }

    })
    return newsubj;
}

我无法将这个 http 调用的执行与 rxjs 同步,请有人帮忙吗? (这里是 rxjs 新手)。谢谢

【问题讨论】:

  • 不要嵌套订阅者

标签: javascript angular rxjs angular5


【解决方案1】:

一种方法是使用forkJoin。它的工作方式类似于Promise.all([...]),但在Observable 字段中。按以下方式修改您的代码:

forkJoin(
        this.dataContextService.dataContext.getFullThing({ param: param }),
        this.dataContextService.dataContext.Table.Query(query => query
            .orderBy(["ID desc"])
            .top(1)
        )
    ).subscribe(
        ([fullThing, number]) => {
            thing = fullThing && fullThing.thing;

            if (number) {
                let increment = number + 1;

                let newObject = new Object({ id: increment, thing: thing });
                this.dataContextService.dataContext.Favorite.Post(newObject).subscribe(result => {
                    newsubj.next(newObject);
                    newsubj.complete();
                });
            }
        }
    );

UPD:根据 cmets 的建议,最好使用 forkJoin 而不是 ForkJoinObservable,因此我编辑了答案以反映这一点。您还可以在此处查看更多forkJoin 使用示例:https://www.learnrxjs.io/operators/combination/forkjoin.html

【讨论】:

  • 我建议改用forkJoin 工厂函数。像ForkJoinObservable 这样的类是一个实现细节,它们一直是removed in RxJS v6
  • 不要嵌套订阅
  • @Jota.Toledo 订阅里面,取决于来自后端的数据。正如我从原始代码中看到的那样,如果 number === null 或 undefined 它根本不应该被调用。
  • 所以?这并不意味着您有义务嵌套订阅
  • @Jota.Toledo 请建议另一种变体作为答案。我很乐意看到它,如果它会更好,我什至会完全删除它。
猜你喜欢
  • 1970-01-01
  • 2021-05-10
  • 2017-06-25
  • 2019-08-16
  • 1970-01-01
  • 2020-10-17
  • 2021-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多