简体   繁体   中英

How to let Angular 6 Http Get method returns an array of observable instead of an observable of array?

Suppose my backend has a route that returns const list = ['Man United', 'Man City'] , and my Angular 6 has http.get() to that route then subscribes with console.log('team: ' + value) .

I will get team: ['Man United', 'Man City'] as the result. Is there a way to convert the observable of array to array of observable? ie, I want to subscribe with console.log('team: ' + value') then I will get team: Man United, team: 'Man City'?

Yes, and it is actually very easy.

import {from} from 'rxjs';
import {flatMap} from 'rxjs/operators';

getCommands(): Observable<string> {
    return http.get(url).pipe(
        flatMap((commands: string[]) => from(commands))
    )
}

PS. This is for current angular 6 version.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM