Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty.

Here's the snippet of my code:

return this.http.get(searchURL)
  .map((res: Response) => res.json())
  .map(json => json.items.forEach(item => {
      new SearchResult(
          item.id,
          item.title,
          item.price
      );
  }) || []);

Answer №1

Ensure you swap out forEach with map and include a return statement:

return this.http.get(searchURL)
  .map((res: Response) => res.json())
  .map(json => json.items.map(item => {
    return new SearchResult(
      item.id,
      item.title,
      item.price
    );
  }))
  .catch((err: Response) => { 
    // handle error
  })

forEach does not provide a return value, whereas map creates a new array by returning items from the callback.

Additionally, the || [] check is unnecessary. If json.items is an array, map will always generate another array. If it is not an array, an error will occur, which should be managed with a .catch block following your .map (specifically for Observable map).

Answer №2

To efficiently handle the returned list, use map for transformation rather than forEach.

Moreover, when dealing with an empty list of items, map will automatically return an empty list without needing to implement || [].

return this.http.get(searchURL)
  .map((res: Response) => res.json())
  .map(json => json.items.map(item => {
    return new SearchResult(
      item.id,
      item.title,
      item.price
    );
  }));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Even after unsubscribing with mqtt.js, the old listener continues to receive messages

Currently, I am utilizing mqtt.js to receive websocket data from an MQTT server. The subscription process is functioning properly, but the challenge lies in changing the topic dynamically by modifying the websocket configuration. The issue arises when, eve ...

The attribute 'commentText' is not found within the 'Comment' data type

Currently, I am immersed in building a user-friendly social network application using Angular 12 for my personal educational journey. Running into an error has left me puzzled and looking for assistance. About the Application: The home page (home.compone ...

Looking to adjust the height of a foreignObject element within an SVG?

Looking to dynamically change the height of a foreignObject within an SVG, while also needing HTML elements inside it (working with ngx-graph). <foreignObject x="1" y="1" width="335" [height]="foreignObjHeight(node.Dat ...

What is the best way to eliminate the # symbol in angular 5 URLs?

Currently, I am working on a project in Angular 5 and I need to remove the hash symbol (#) from my URL. The current URL looks like this: http://localhost:4200/#/product/add. While it works fine after being published on my domain, I encounter a 404 error ...

Auto-complete feature not populating the input field in Google Chrome

Within my register form, I have various INPUT tags present. One of these INPUTs has the name email. <input type=text name=email id=email> When filling out this form in Chrome, I encounter a peculiar behavior. Upon clicking on the email input field ...

How can multiple arguments be passed to a function using JQuery's post method?

I can't seem to figure out how to pass multiple arguments to a function using jQuery's post method. It might sound like a silly question, but I'm struggling with it. Currently, my code looks something like this: $.post("<?php echo site_ ...

Utilizing a shared service for multiple JSON datasets in AngularJS: A beginner's guide

After successfully creating a service that retrieves data from a local JSON file and uses it in a controller to display it in the browser, everything seems to be working well. Here is the code snippet: JavaScript Code: var myApp = angular.module("myApp", ...

Sorting through items based on several URL parameters

In an effort to be concise yet clear, I am working on an ecommerce website using Next.js and Shopify. This site features products that need to be filterable based on certain attributes. I retrieve products from the Shopify API, each with its own Product Ty ...

Exploring the Scope of a Directive within an HTML Element's Event Handler

I devised a custom Directive for utilizing an element as a 'dropzone' with native HTML Drag & Drop functionality. Custom Directive Source Code import { Directive, ElementRef, OnInit, Output, EventEmitter, ViewChild } from '@angular/co ...

Updating state with new data in React: A step-by-step guide

Recently, I delved into the world of reactjs and embarked on a journey to fetch data from an API: constructor(){ super(); this.state = {data: false} this.nextProps ={}; axios.get('https://jsonplaceholder.typicode.com/posts') ...

Exploring the possibilities of implementing the .map() function on a JSONArray within a ReactJS project using ES

When I receive a JSONArray from the server, my goal is to use .map() on it in order to extract key-value pairs of each object within the array. However, when I try to implement this code, I encounter an error stating "files.map is not a function". Can some ...

Customize the file name for exporting data from a Syncfusion grid view with Angular

In my Angular (v6.8) application, I have implemented a Syncfusion grid view from Syncfusion. When downloading the grid content as an Excel sheet, the default file name displayed is "Export.xlsx". I am trying to set a custom file name for the download proce ...

"Enhancing User Experience with jQuery: Implementing a Smooth Scroll Feature with Current

I could really use some guidance on this issue that's been causing me trouble. Take a look at this fiddle for reference: http://jsfiddle.net/NtUpw/ Currently, the code is functioning as expected. However, I'm facing an issue where when the curre ...

My date function in Node JS is throwing an error, can someone please help me troubleshoot?

I encountered an error with new date(); while working with node js and express npm plugin. I built a variable date but faced some compilation errors. This is my code .js var update_time = new Date(); update_time.formatDate("y/m/d"); When I run ...

Using Vue.js, send information from an Ajax request to a Laravel controller for processing

As someone new to development, I have a little confusion with handling data from a multi-step form in an AJAX request on my controller. While I've been able to successfully collect all form inputs at once, I'm struggling to use the data from $req ...

Angular Material Flex is not providing the correct size

There seems to be a problem with certain values for setting the flex property in the Angular Material layout library. The issue is clearly demonstrated in this straightforward example. By clicking through, you can observe that some values display correctl ...

Error encountered during Atom execution - The command '/usr/bin/env: 'node' was not found in the directory

Just starting out with coding on Atom and I'm stuck dealing with the same error message every time I try to run my Javascript code. bash: line 1: node: command not found /usr/bin/env: ‘node’: No such file or directory I've searched for solu ...

Showcasing a JSON file in the interface using $http in AngularJS

I am a beginner in angularjs (and programming). I am attempting to showcase a json file on my view (home.html) using $http and ngRepeat, but unfortunately, it is not working as expected. Upon inspecting the angular responses, I noticed that there are numer ...

Ensure that the input remains below ten

My goal here is to ensure that the value in an input element is a non-zero digit (0<x<=9). Here's the HTML tag I'm using: <input type="number" class="cell"> I've experimented with various JavaScript solutions, but so far none h ...

Combine two closely related functions into a single function

I'm dealing with two very similar functions: setEndTimesAndStartTimes(pricerules: PriceRule[], type: string) { this.endTimes = []; this.startTimes = []; pricerules.forEach(pricerule => { if (type === 'end') { ...