Undefined value after RxJs mapping Code Answer

Why am I getting undefined inside subscribe method? I am trying to combine to data sources. Customers and Categories. I am trying to fill Category property of customer based on matching CategoryId from Category collection.

STACKBLITZ

constructor(private http: HttpClient) {}
  ngOnInit() {
    const custurmersWithCategory$ = combineLatest([
      this.http
        .get<ICustomer[]>(
          "https://www.json-generator.com/api/json/get/cgqEBPcHtu?indent=4"
        )
        .pipe(delay(1000)),
      this.http.get<ICategory[]>(
        "https://www.mocky.io/v2/5db4195d300000520057b70b"
      )
    ]).pipe(
       map(([customers, categories]) => {
         customers.map(
          customer =>
            ({
              ...customer,
              Category: categories.find(
                c => customer.CategoryId === c.CategoryId
              ).category
            } as ICustomer)
        );
      })
    );

    custurmersWithCategory$.subscribe(data => {
      console.log(data);// why is this undefined?
    });
  }

Answer

You aren’t currently returning anything from map, thus you get undefined. As explained here: https://stackoverflow.com/a/41743119/6294072 your code translates to something like:

function (foo) { bar; }

which doesn’t return anything at all. So add

return customers.map( ...

and it will actually return some values.

STACKBLITZ

As per comment if not wanting to add the return, you can just remove the curly brackets from inside map.

STACKBLITZ

As a further comment, like mentioned in the answer I linked, this has nothing to do with rxjs map, but rather how arrow functions work 🙂

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji