Jake Shakesworth
Jake Shakesworth

Reputation: 3555

How to map an observable to another

I've looked at the RxJs docs and performed a search for this and cannot (surprisingly) find examples of what I'm trying to do.

Basically, I have two services. One services consumes the other service and needs to map the response of the consuming service to another type.

Example code from an Angular app:

@Injectable()
export class EmployeesService {

  BASE_URL = 'http://foo.bar.com/api/getEmployees';

  constructor(private http: HttpClient) {
  }

  get(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.BASE_URL);
  }
}


@Injectable()
export class MyEmployeeService {

  constructor(private svc: EmployeesService) {
  }

  get(): Observable<IMyEmployee[]> {
    return this.svc.get().map(
        (employees:IEmployee[]) => employees.forEach(employee => this.mapEmployeeToMyEmployee(employee))
    );
  }

  private mapEmployeeToMyEmployee(employee: IEmployee): IMyEmployee {
    return {
      ... simple property mapping to transform IEmployee to IMyEmployee
    };
  }
}

However, in "MyEmployeeService" the Typescript compiler is complaining "Returned expression type Observable(void) is not assignable to type Observable(IMyEmployee[]).

Even if I were to add return statements within the map operation I'm still getting the same complaints. What am I doing wrong here?

Upvotes: 1

Views: 542

Answers (1)

Pearman
Pearman

Reputation: 1068

It's your single line lambda:

(employees:IEmployee[]) => employees.forEach(employee => this.mapEmployeeToMyEmployee(employee))

employees.forEach(...) returns undefined. Since your using the format (...)=>... instead of (...)=>{...} the lambda is returning the value of your single statement (undefined).

Change it to this:

(employees:IEmployee[]) => employees.map(employee => this.mapEmployeeToMyEmployee(employee))

map is like forEach, except for that it builds a new array from the returned value of employee => this.mapEmployeeToMyEmployee(employee).

Upvotes: 3

Related Questions