Search code examples
javascriptangular-httpclient

How do I modify items in a service before returning it back to angular client?


When returning data from my data-access service I only get undefined after modifiying the response. What is wrong with my pipe?

.pipe(
  map(result => result['dimensions']),
  map(result => result.forEach(element => {
    result.dimensionItems = element.dimensionItems.map(item => {
      item.parentId = result.dimensionId;
      item.dimensionItemId = Math.floor(Math.random() * 1000);
    });
  })),
  tap(result => console.log('Aiiiaiiii: ', result)),
  catchError(this.handleError)
);

Solution

  • The forEach returns undefined [1], so you'll need to change your code to this:

    .pipe(
      map(result => result['dimensions']),
      map(result => {
        result.forEach(element => {
          result.dimensionItems = element.dimensionItems.map(item => {
            item.parentId = result.dimensionId;
            item.dimensionItemId = Math.floor(Math.random() * 1000);
          });
        });
        return result; // You need to return the result after the foreach.
      }),
      tap(result => console.log('Aiiiaiiii: ', result)),
      catchError(this.handleError)
    );
    

    As you can see from the comment, you need to return the result after you have manipulated it with the forEach.

    References [1] - Array.prototype.forEach() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach