0

I have the following code that is working, but I feel like there is a much simpler way of doing this with rxjs. Does anyone know how this can be simplified? The main reason for the complexity is I need to run the custom constructor on each item in the array before I can return it to the subscribing method. (Angular 8.2.3, Typescript 3.5.3, rxjs 6.4.0)

getAllthings() : Observable<Object>{
    const apiUrl = `${this.baseUrl}/things`;
    return this.http.get<Array<Thing>>(apiUrl).pipe(
      map((itemsArray) => {
        itemsArray.forEach(function(item, index, array) {
          array[index] = new Thing(item);
        });

        return itemsArray;
      }));
  }

2 Answers 2

4

Instead of reassigning each index inside the .forEach callback, use .map instead, to transform every element into a Thing:

return this.http.get<Array<Thing>>(apiUrl).pipe(
  map(itemsArray => itemsArray.map(item => new Thing(item)))
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this, I knew there was something simple I was missing.
0

An addition to @CertainPerformance solution, you can remove type declaration on the function and let typescript infer the type

Overally your getAllthings() will reduce to

getAllthings = () =>
  this.http.get<Array<Thing>>(`${this.baseUrl}/things`).pipe(
      map(itemsArray => itemsArray.map(item => new Thing(item))
  )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.