angulartypescriptrxjsrxjs5rxjs-observables

How to take some of the properties of an Observable and assign them to another Observable using RxJS operators


I have an employee$ Observable and a personalInformation$ Observable. personalInformation$ is a subset of employee$ and I want to map the matching properties of employee$ to personalInformation$. The observables have many more fields but for simplicity I made them shorter here.

export interface EmployeeModel {
  id: number;
  personalEmail: string;
  firstName: string;
  lastName: string;
  remote: boolean;
  office: string;
}
employee$: Observable<EmployeeModel>;

Personal Information

export interface PersonalInformationModel {
  id: number;
  personalEmail: string;
  firstName: string;
  lastName: string;
}
personalInformation$: Observable<PersonalInformationModel>;

This is what I tried but did not work.

    this.personalInformation$ = this.employee$
      .pipe(
        map((data) => {
          data!.id,
          data!.personalEmail,
          data!.firstName,
          data!.lastName
        }),
        catchError(err => {
          const message = "Could not load record";
          this.logService.error(message, err)
          return throwError(() => new Error(err));
        })
      );

Solution

  • With an arrow function, you aren't returning the object correctly. You nee another set of parenthesis around the 'squigly braces {}' in your map.

    this.personalInformation$ = this.employee$
          .pipe(
            map((data) => ({
              id: data!.id,
              personalEmail: data!.personalEmail,
              firstName: data!.firstName,
              lastName: data!.lastName
            })),
            catchError(err => {
              const message = "Could not load record";
              this.logService.error(message, err)
              return throwError(() => new Error(err));
            })
          );