1

I am working on a data service that gets data from a REST service. Is there a way to receive an Observable of an array of one type of object but return an Observable of a different type of array? I would think this is what mergeMap does but I'm having trouble understanding how to accomplish this.

Something like this:

@Injectable()
export class MyDataService {
  constructor(private http: HttpClient) { }

  getThings(): Observable<B[]> {
    return this.http.get<A[]>(url)
    mergeMap(x => [x + <B>{foo: x.bar});
  }
}

In C# I would just use a LINQ expression to select a new object. How can I do the same thing in Angular? Perhaps the service can just simply return the Observable array of type A and the consumer that's subscribed to the service can take care of the mapping somehow? Would that be the better approach?

1 Answer 1

1

It depends what/where you want to map. For example you can type hint the .map operator:

.map<A, B>(v => /* transform A to B */)

You can do the same with mergeMap:

.mergeMap<A, B>(v => /* transform A to Observable<B> */)
Sign up to request clarification or add additional context in comments.

2 Comments

I found I had to do a mapping twice to get what I wanted. The first map call 'x' is a A[]. But I need to change each A into a B so I mapped x and returned a new B using the y variable in the second map. Is there a better way? .map(x => x.map(y => <B>{ foo: bar }))
I think you can return also .map(x => x.map(y => { foo: bar })) as B[] which is maybe more readable

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.