同步嵌套订阅的角度 5



我有一个函数,如下所示:

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 新手在这里(。谢谢

一种方法

是使用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:正如评论中所建议的,最好使用forkJoin而不是ForkJoinObservable所以我编辑了我的答案来反映这一点。您还可以在此处查看更多forkJoin使用示例:https://www.learnrxjs.io/operators/combination/forkjoin.html

最新更新