以角度5同步嵌套订阅

时间:2018-04-06 17:12:02

标签: javascript angular rxjs angular5

我的功能如下:



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;
}
&#13;
&#13;
&#13;

我无法与rxjs同步此http调用的执行,可以请别人帮忙吗? (rxjs新手在这里)。感谢

1 个答案:

答案 0 :(得分:0)

这样做的一种方法是使用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

相关问题