0

To simplify the problem i have used numbers and strings here. The code:

const numbers$:Observable<number[]> = of([1,2,3]);
const strings: string[] = ["a","b"];

function getStrings(): Observable<string>[]{
   return numbers$.pipe( 
     map((numbers: number[]) => {
       const strings$: Observable<string>[] =  strings.map(s => of(s));
       return strings$;
     }),
  )
}

getStrings().subscribe(x => console.log(x))

The error i am getting is: Type 'Observable<Observable<string>[]>' is missing the following properties from type 'Observable<string>[] How can i get Observable<string>[] from getStrings function? I have tried to use flatMap, switchMap but unable to get the perfect combination.

Stackblitz

7
  • 2
    Try using mergeMap instead of map. Commented Mar 19, 2020 at 15:15
  • didn't solve the problem Commented Mar 19, 2020 at 15:19
  • 2
    Using Observable<string>[] means an array of Observable<string> which is not what you're returning right now. Maybe you wanted this instead Observable<string[]>? Commented Mar 19, 2020 at 15:23
  • No i want Observable<string>[] because in my application i will use this in forkJoin Commented Mar 19, 2020 at 15:28
  • @martin You are right, i want Observable<string[]>, not Observable<string>[] Commented Mar 19, 2020 at 15:31

2 Answers 2

1

You'll need to use mergeMap() and forkJoin():

function getStrings(): Observable<string[]>{
   return numbers$.pipe( 
     mergeMap((numbers: number[]) => {
       const strings$: Observable<string>[] =  strings.map(s => of(s));
       return forkJoin(strings$);
     }),
  )
}

getStrings().subscribe(x => console.log(x))

https://stackblitz.com/edit/rxjs-dzvsbh?file=index.ts

Sign up to request clarification or add additional context in comments.

Comments

0

So as I understand you want to "zip" two lists together, via observable ?

I can offer you this one


    const numbers$: Observable<number[]> = of([1, 2, 3]);
    const strings$: Observable<string[]> = of(['a', 'b']);

    const combined$: Observable<any> = zip(numbers$, strings$)
      .pipe(
        map(([numbers, strings]) =>
          numbers.length > strings.length ?
            numbers.map((value, index) => [value, strings[index]]) :
            strings.map((value, index) => [numbers[index], value]))
      );

    combined$.subscribe(value => console.log(value));

This will log: [ [ 1, "a" ], [ 2, "b" ], [ 3, null ] ]

2 Comments

Basically no, because in real example strings$ is dependent on numbers$ response.
@Aamir ok, sorry for misunderstanding :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.