用forkJoin进行条件可观察

chr*_*ris 1 javascript observable rxjs typescript angular

在某些情况下,我可能需要或不需要将可观察值添加到列表中。然后,我要forkJoin使用我拥有的可观察对象,以便在所有数据可用后就可以加载页面。

let observables: Observable<any>[] = [];

observables.push(this.taskService.getStep(this.housingTransactionId, this.task.stageReferenceId, this.task.stepReferenceId));

if (this.task.associatedChatThreadId) {
    observables.push(this.messageHubService.getChatThread(this.housingTransactionId, this.task.associatedChatThreadId));
}

if (this.task.associatedDocuments && this.task.associatedDocuments.length > 0) {
    this.task.associatedDocuments.forEach(documentId => {
        observables.push(this.documentHubService.getDocumentProperties(this.housingTransactionId, documentId));
    });
}

Observable.forkJoin(observables)
    .subscribe(([step, chatThread, ...documents]) => {

        this.step = step;           
        this.chatThread = chatThread;           
        this.documents = documents;

        this.isPageLoading = false;

    }, error => {
        this.isPageLoading = false;
        console.log(error);
    });
Run Code Online (Sandbox Code Playgroud)

我得到的问题是,如果我没有this.task.associatedChatThreadId,那么可观察对象将不会添加到列表中,并且在forkJoin执行时,...documents它们将位于chatThreadSubscribe方法中属性的位置(好吧,第一个文档! )。

有没有办法确保来自a的响应的定位forkJoin?还是我/我可以使用其他方法?

mar*_*tin 6

如果不满足条件,您可以很容易地添加Observable.of(null)带有null值的哑巴,以保持相同的响应顺序:

if (this.task.associatedChatThreadId) {
    observables.push(this.messageHubService....);
} else {
    observables.push(Observable.of(null))
}
Run Code Online (Sandbox Code Playgroud)

然后在订阅中,您可以检查chatThread === nullbeauauese是否总是存在于相同位置。

或者,您可以observables使用一些额外的对象包装每个Observable 对象,这将使它在订阅服务器中唯一可识别,但是不必要地变得复杂,因此我个人会坚持使用第一个选项。