Search code examples
angularrxjs

Observable<Any> transformation to Observable<Bar[]>


I'm pretty new to angular, I'm trying to transform result of an Observable any to Observable<Bar[]> but I have an error: Type Bar is not assignable to type 'ObservableInput any

find(id: string): Observable<Bar[]> {
    return this.findFoo(id)
        .pipe(
          map(data => data.result.entities)
          switchMap((data) => {
            let bar: Bar = {
              id: data.field,
              entity: data
            };
            return bar;
          })
        );
}

Any idea how to do ?


Solution

  • Do it like so to be Typescript compliant 👌🏼:

    find(id: string): Observable<Array<Bar>> {
        return this.findFoo(id)
            .pipe(
              map((response: Array<any>) => {
                return response.result.entities.map((entity: any) => {
                  return {
                    id: entity.field,
                    entity: entity
                  } as Bar
                }
              }
            );
    }
    

    By the way, why does the find method return (Array of) any? Couldn't this be type safe as well?