Home > Mobile >  Unable to transform Observable values using map
Unable to transform Observable values using map

Time:06-20

I'm trying to get a list from HttpClient in Angular but I'm having a problem with transforming the data from an Observable.

I have tried with static values also, but I'm getting the same result. When I try to transform values in an Observable using map() I get unmodified results back. See these two examples:

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

// First example:
const observableOne$: Observable<number[]> = of([1, 2, 3]);
observableOne$.pipe(
  map((items: number[]) => {
    console.log('This will be ignored');
    return items.map((item: number): number => item   100);
  }),
  map((items: number[]) => {
    console.log('This will also be ignored');
    items.push(4);
  })
);
observableOne$.subscribe((items: number[]) => console.log('First:', items));
// Output will be:
// First: [1, 2, 3]

// Second example:
const observableTwo$: Observable<number> = from([1, 2, 3]);
observableTwo$.pipe(map((item: number) => item   100));
observableTwo$.subscribe((items: number) => console.log('Second:', items));
// Output will be:
// Second: 1
// Second: 2
// Second: 3

Any suggestions?

CodePudding user response:

Using a pipe() will not modifiy the original Observable. Instead it creates a new Observable which needs to be subscribed by someone. So when you are subscribing to ObservableOne$, you just get the original emitted values.

You have to subscribe to the Observable returned by the pipe.

const observableOne$: Observable<number[]> = of([1, 2, 3]);

observableOne$.pipe(
  map((items: number[]) => {
    console.log('This will be ignored');
    return items.map((item: number): number => item   100);
  }),
  map((items: number[]) => {
    console.log('This will also be ignored');
    items.push(4);
    return items
  })
).subscribe((items: number[]) => console.log('First:', items));

Also notice that you missed the return statement in your second map. If you don't have a return statement inside a map, it will just return undefined which will be passed further down the chain.

  • Related