I am trying to get data from the server using rxjs:
class HolidaysService {
constructor() {
this.restService = newRestService();
}
public getHolidaysByYear(year: number): Observable<Date[]> {
const endpoint = `/get${year}`;
return this.restService.GET(endpoint, { cache: true })
.pipe(map(dates: any)=> dates.map((item: string) => new Date(item)))
}
public getHolidaysByYears(years: number[]): Observable<Date[]> {
const requests = years.reduce((acc,v)=>acc.concat(this.getHolidaysByYear(v)),[])
return forkJoin(...requests).pipe(scan((acc,v)=>acc.concat(v), []))
}
}
// We call it:
const holidayService = new HolidaysService();
const substriction1 = holidayService.getHolidaysByYear(2020)
.subscribe(
res => console.log('res', res),
err => console.warn(err)
);
substriction1.unsunscribe();
The console displays res and the data itself. Now I want to get information for several years using rxjs-analogue of promise.all:
const substriction2 = holidayService.getHolidaysByYears([2019,2020])
.subscribe(
res => console.log('res', res),
err => console.warn(err)
);
substriction2.unsunscribe();
And nothing works. I do not see res in the console and data. What could be the mistake?
This is how you would write Promise.all
analogue in the RxJS with forkJoin
:
public getHolidaysByYears(years: number[]): Observable<Date[]> {
const requests = years.map(year => this.getHolidaysByYear(year));
return forkJoin(requests).pipe(concatAll());
}
Note that I am using concatAll
operator, because forkJoin(requests)
will give you Observable<Date[][]>
, that is Array of holiday dates per year. Since your return type is Observable<Date[]>
, that's why I am using concatAll
operator to concatenate the resulting Arrays and get the Observable<Date[]>
instead of Observable<Date[][]>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.