本文介绍了RxJS:Observable 数组的 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 Angular4 应用程序中使用 Observables 时遇到以下情况,但我无法开始工作:我想为概览页面收集所有预订日的摘要数据.获取所有天数是一个 Observable,每天都有一个我必须检索的当天预订列表 - 再次是一个可观察的来源.我从这个列表中计算出当天的摘要.我想在一个结果 observable 中发出所有这些摘要.

I have the following situation using Observables in my Angular4 app that I just can't get to work: I want to gather summary data of all my booking days for a overview page. Getting all the days is an Observable, and each day has a list of bookings of that day that I have to retrieve - again an observable source. From this list I calculate a summary of the day. All these summaries I want to emit in a resulting observable.

我尝试了很多更复杂的事情,但总是没有等待完成的内部观察结果,我得到了空洞的总结.我已经回到了基础,按照这些思路应该可以工作:

I have tried lot's of more complicated things, but always the inner observables where not waited on to complete and I got empty summaries. I have gotten back to the basics, and something along these lines should work:

getSummaries(): Observable<BookingDaySummary[]> {
    return this.bookingService.getBookingDays().take(1).mergeMap(
        days => this.calculateSummaryOfDays(days)
    )
};

private calculateSummaryOfDays(days: BookingDay[]): Observable<BookingDaySummary[]> {
    const summaries$ = days.map(day => this.calculateSummary(day));
    // I'm aware that the next line is not correct.
    // Essentially I want the array of observables to complete
    // and have an array of the resulting values.
    return Observable.merge(summaries$);
}

private calculateSummary(day: BookingDay): Observable<BookingDaySummary> {
    // ... logic to get summary from one day
}

然而,summaries$ 的类型是 Observable 而不是 Observable.所以这一切都归结为:我如何从 [Observable] 制作 Observable ?

However, the type of summaries$ is Observable<Observable<BookingDaySummary> and not Observable. So it all boils down to: How do I make an Observable<T[]> from [Observable<T>]?

另外:我在 .map 中使用的最内部方法是否应该返回一个 Observable 或者只是在打算生成 Observable 时将传入类型映射到 T 代码>?

Also: Should the most inner method I use in .map return an Observable or just be a map on the incoming type to T when intending to produce an Observable<T>?

推荐答案

forkJoin 就是这样做的.为您的 T 使用字符串:

forkJoin does this. Using String for your T:

import { of, forkJoin} from 'rxjs';
import { Observable } from 'rxjs'

const source:Array<Observable<String>> = [of('A'), of('B'), of('C') ];

const source2:Observable<String[]> = forkJoin(source);

source2.subscribe((res=>console.log(res)));

https://stackblitz.com/edit/arrayofobs2obsofarray?file=index.ts

这篇关于RxJS:Observable 数组的 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:44