Fetching JSON Data Using Angular 5

When it comes to retrieving JSON data using http.get in TypeScript, I've encountered an issue. Specifically, I'm struggling to extract specific values from my key within Angular.

The JSON data format I'm working with looks like this:

[
    {
        "id": 1,
        "name": "Albany",
        "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g",
        "price": 15.49,
        "category": "Food",
        "type": "Breads",
        "image": "data:image/jpeg;base64,/9j/4AAQSkZJ..."
    },
    {
        "id": 2,
        "name": "Blue Ribbon",
        "manufacture": "Blue Ribbon Brown Plus Low Gi Bread 700g",
        "price": 13.99,
        "category": "Food",
        "type": "Breads",
        "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."
    }
]

My service in Angular is structured as follows:

export class ProductService {

  prodType: ProductModel;
  productList: object;

  prodList: Array<ProductModel> = [];
  prodMap: Map<number, ProductModel>;

  constructor(private http: HttpClient) {}

    getAllProducts(): Array<ProductModel>{
    this.http.get<Array<ProductModel>>('/product/service/send/all/products').subscribe(
      data => {

        console.log(data);

      },
      error => {
        console.error("HTTP FAILURE ERROR!!!");
      }
    );
    return this.prodList;

  }

  getProductByType(productSearch: string){

    this.productList = this.prodList.find(x => x.getType() == productSearch);
    console.log(this.productList);
  }  
}

The structure of the ProductModel class is defined as:

export class ProductModel {

    private id: number;
    private name: string;
    private manufacture: string;
    private price: number;
    private category: string;
    private type: string;
    private image: string;
    // getters and setters

Now, the big question arises: how can I search through my JSON data for product types specifically related to milk and only display those products via console log?

This problem has been a challenge, as similar solutions I have come across were not helpful. Any suggestions or guidance would be greatly appreciated!

Answer №1

To begin, store the HTTP response in a class variable and then proceed to refine the data by filtering it before displaying the filtered array items on the console.

export class ProductService {

  prodType:ProductModel;
  productList:object;

  prodList: Array<ProductModel> = [];
  prodMap: Map<number, ProductModel>;

  constructor( private http: HttpClient ) { }

    getAllProducts() {
    this.http.get<Array<ProductModel>>('/product/service/send/all/products').subscribe(
      datas => {

        this.prodList = datas;

      },
      error => {
        console.error("HTTP FAILURE ERROR!!!");
      }
    );    
  }

  getProductByType( productSearch:string ): Array<ProductModel>{

    let filteredProducts:Array<ProductModel> = this.prodList.filter(product => product.type == productSearch);

    filteredProducts.forEach(product=> console.log(product);

    return filteredProducts;

  }  
}

Answer №2

To enhance the functionality, you have the option to include the map and customize the response received from the http get request by applying filters before populating the list. Alternatively, if you prefer to segregate these tasks, it is advisable to split the process into two distinct methods - one for retrieving the raw list of products and another for filtering the data accordingly.

 obtainAllItems(): Array<ItemModel>{
    return this.http.get<Array<ItemModel>>('/items/service/retrieve/all/items').map(data => data.filter(value => value.category == 'clothing')).subscribe();
  }

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

Expanding constructor in TypeScript

Can the process described in this answer be achieved using Typescript? Subclassing a Java Builder class This is the base class I have implemented so far: export class ProfileBuilder { name: string; withName(value: string): ProfileBuilder { ...

Encountering a TypeScript error when trying to establish a connection to MariaDB using node

working with mariadb npmjs version: 2.1.2 import mariadb from "mariadb"; const pool = mariadb.createPool({host: process.env.DBHOST, user: process.env.DBUSER, password: process.env.DBPASS, port: process.env.DBPORT, connectionLimit: process.env.DBCONNLIMIT, ...

An issue arises when trying to update state using useState in TypeScript

In our system, we have a state that contains an array of objects: interface Product { id: number; status: boolean; color: string; price: number; } const productList: Product[] = [ { id: 1, status: true, color: 'yellow', ...

What is the correct method for implementing a To-Do List?

I am trying to create a to-do list, but I am facing an issue with using splice to remove a specific item e.target.item. It seems like it would be easier if I were using Angular 5. Can anyone assist me with this problem? Thank you. import React, { Compone ...

Encountering a SyntaxError when attempting to install Angular CLI globally using npm [@angular/cli]. The error specifically mentions an unexpected token "}" in the

When I run the command npm install -g @angular/cli, I encounter an error. verbose stack SyntaxError: Unexpected token } in JSON at position 5285 while parsing near '...uebird-0.7.12-1.tgz"}},"0.7.12-2":{"name...' 353 verbose s ...

Can you explain the contrast between the two model configurations when making API calls?

Within my service file, I have a method that calls an API: getDetail(id: number): Observable<any> { return this.http.get<any>("api/detail/" + id, { responseType: 'json', observe: 'response' }) } Curren ...

Using Json, post, and curl in PHP

Could you please refrain from closing this question before looking into my particular issue? I have come across several similar problems, but none of the solutions have worked for me. My main goal is to send a json_encoded array using the POST method with ...

Tips on storing and retrieving data between pages in Ionic 4/5: Saving data to a service and accessing it from a

Looking for assistance from the community I am trying to pass data between pages using a service in Angular. Here is the code for the parent component.ts file: import { Component } from '@angular/core'; import { ShareService } from '../sh ...

Crafting questions to uncover the correct application of the concept of "side effects" in ngrx/effects

I am seeking clarity on whether my approach is correct. After researching examples online, I have noticed a common pattern in handling add and delete actions in both the state and remote database: effects.ts: @Effect() add$ = this.action$ .ofType(ADD ...

Inconsistencies in MongoDB $graphLookup aggregation result order and sorting issues

The way my aggregation operation is structured, it's producing the correct result, but there's a problem with the order. Every time I refresh, the nested array (posteriorThread) switches up the document sequence randomly, and it's baffling! ...

Stop echo JSON from being displayed on the screen directly

When I use an Ajax call to pass a JSON back, the contents end up in my div . The issue is that the same "echo" statement that returns the JSON also displays it directly on my page. How can I prevent this unwanted behavior? Here is the code snippet: Form S ...

Learn how to access keys and values within a JSON object by utilizing Json.Net in C# programming

Greetings! I am facing a situation where I have a JSON data structure like the one below: { "Id": " 357342524563456678", "title": "Person", "language": "eng", "questionAnswer": [ { "4534538254745646.1": { ...

Using Angular to Bind JSON Data

I'm currently in the process of evaluating different JS frameworks for a project and I find myself torn between Angular and Ember. As I continue to explore Angular, I have a specific question regarding data binding to an external json file stored on S ...

Refresh the UITableView after finishing the delete operation on the detail view

I am facing an issue with my UITableView that fetches data from MySQL using JSON. The tableview has a detail view with two actions - edit and delete. Editing works fine, but when I delete an item, the data is removed from MySQL successfully, however, the U ...

Having trouble getting Typescript code to function properly when using commonjs style require statements

I am completely new to Typescript, Node.js, and Express. Following the instructions outlined in this tutorial (https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript), I set up my project exactly as described there. The ...

Testing an Angular component using Jasmine within a project with multiple module files

Struggling to troubleshoot an issue I'm facing with my testing setup. The service tests that rely solely on the httpclient are running smoothly. However, when attempting to test a component with dependencies, errors start popping up without even execu ...

Tips on invoking a child component's function from the parent component

I'm struggling to comprehend, Is there a way to trigger a function within a child component by clicking on a button in the parent component? ...

Serialization of AspNetCore EntityModel to Json is not possible

I am currently tackling a project in AspNetCore involving EntityFrameworkCore and I am looking to utilize Ajax to retrieve an object. However, my controller is encountering issues when trying to serialize this object into Json format, causing my Ajax call ...

Sharing data between components in Angular 2 using services

I'm having trouble passing data from the 'first' component to the 'second' component using a service. Despite setting the data in the constructor of the 'first' component, when I try to access it in the 'second' ...

Tips on finding the key associated with a specific value

When a form is submitted, one of the fields being sent is an ID number instead of the name for easier processing by the server. For example: HTML dropdown select <select ng-model="myColor" class="form-control" ng-options = "color.ID as color.color ...