Narasimhan
Narasimhan

Reputation: 83

How to convert Observable<Product[]> to Observable<Product>[] without subscribe?

In my current angular project I have a service that returns Observable<Product[]>. I would like to convert that stream to an array of Observables of single Product. I want to achieve this using pipe operators, without subscribing to the original stream.

From Observable of <entity[]> to array of Observables of entity

Upvotes: 1

Views: 1401

Answers (1)

JJWesterkamp
JJWesterkamp

Reputation: 7916

When you're using pipe on an observable, you'll always get back a new observable, never an array. You can access the Product[] and map it to an (Observable<Product>)[] without any problem, but the result will still be wrapped in another observable:

import { of } from 'rxjs';
import { map } from 'rxjs/operators';

interface Product {
    id: number;
}

const products: Observable<Product[]> = of([
    { id: 1 },
    { id: 2 },
    { id: 3 },
]);

products
    .pipe(map(ps => ps.map((p) => of(p))))
    .subscribe((observables: Observable<Product>[]) => {
        // In here you can access the array of observables:
        console.log(observables);
    })

Instead of subscribing to the observable, you could also tap within pipe to access the result of map(), but the result will still only be accessible from within an Observable context:

// ...
import { map, tap } from 'rxjs/operators';
// ...

const x = products
    .pipe(
        map(ps => ps.map((p) => of(p))),
        tap((observables: Observable<Product>[]) => {
            // In here you can also access the array of observables:
            console.log(observables);
        }),
    );

But x is still an observable:

const x: Observable<Observable<Product>[]>

or equivalently but maybe slightly more understandable:

const x: Observable<Array<Observable<Product>>>

Upvotes: 3

Related Questions