How to extract a specific property from data using Angular's HttpClient-subscribe

It seems like this question has been asked before, but I can't seem to find the answers or know what terms to search for.

I have a JSON file structured like this:

{
  "pages": [{
      "displayname": "PageA",
      "url": "http://google.de",
      "icon": "iconZ"
    },

    {
      "displayname": "PageB",
      "url": "http://www.pageb.co.uk",
      "icon": "iconY"
    }
  ],
  "icons": [{
      "alias": "iconZ",
      "filename": "iconZ.svg"
    },

    {
      "alias": "iconY",
      "filename": "iconY.svg"
    }
  ]
}

Currently, I am using the HttpClient (referred to as httpService) to fetch this data from the file.

this.httpService.get('./assets/pageconfig.json').subscribe(
      data => {
        this.arrAdress = data as string[];
      },
      (err: HttpErrorResponse) => {
        console.log(err.message);
      }
    );

I am looking to use the 'pages' content in my ngFor loop in the Frontend and I also need an array of the icon data for use in the Backend. How can I extract this data based on the properties?

Appreciate your assistance, Elias

Answer ā„–1

If your pageconfig.json file is utilized in both the front and backend of your application, and you only require the "pages" attribute for your Angular app, you can retrieve it like this:

this.httpService.get('./assets/pageconfig.json').subscribe(
  data => {
    this.arrAdress = data.pages;
  },
  (err: HttpErrorResponse) => {
    console.log(err.message);
  }
);

There is no need to explicitly specify the data type.

Alternatively, you could utilize rxjs observable map chaining to parse the data and extract only the relevant information:

import { map } from 'rxjs/operators';

this.httpService.get('./assets/pageconfig.json')
  .pipe(map(data => data.pages))
  .subscribe(pages => {
    this.arrAdress = pages;
  }).catch((err: HttpErrorResponse) => {
    console.log(err.message);
  });

I trust this solution aligns with your requirements.

Answer ā„–2

It is recommended to replace string[] with an Array of objects or any type.

this.httpService.get('./assets/pageconfig.json').subscribe(
      data => {
        this.arrAdress = data;
      },
      (err: HttpErrorResponse) => {
        console.log(err.message);
      }
    );

sendData(icon){
    const matched = this.arrAdress.icons.filter(iconObj => iconObj.alias === icon);
    console.log(matched);
  }

 **Template:**

  <div *ngFor="let adress of arrAdress?.pages;" (click)="sendData(adress.icon)">
    <span>{{adress.displayname}}</span>
  </div>

Answer ā„–3

If you are facing this issue, there are two solutions available for you.

Imagine that when you use the httpClient.Delete() option, it gives you an observable object with the employeeId as a property.

Solution 1 (for example)

Declare a local variable and assign the data to it using the let statement

(e.g. let response: any = data;).

delete(employee: any) {
    this.employeeService.deleteEmployee(employee.id)
        .subscribe(
            data => {
                let response: any = data;
                // now you can use response.employeeId
            },
            (error) => {
                console.log(error)
            },
            () => {
                console.log("The operation has been completed")
            }
        );
}

Solution 2 (for example)

Specify the type as any (e.g. (data : any) for the received response

delete(employee: any) {
    this.employeeService.deleteEmployee(employee.id)
        .subscribe(
            (data: any) => {
             // now you can use data.employeeId
            },
            (error) => {
                console.log(error)
            },
            () => {
                console.log("The operation has been completed")
            }
        );
}

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

Transmitting End of Transmission through Remote Socket

Iā€™m currently working on processing data in R received from a TCP Server Socket using JSON formatting. My script successfully establishes a connection with the server using: socketConnection(host = "whateverhost", port = "8080", server = FALSE, encodi ...

Utilizing JSON encoding with produces={"application/json; charset=UTF-8"} and the ObjectMapper technology

I'm in the process of developing a microservice with Spring MVC and Spring Boot that returns results in JSON format. Currently, I have implemented the following action: @RequestMapping("/checkUsers") public String checkLogin() throws JsonProcessi ...

In Angular, the dropdown in reactive forms will not populate unless there is some interaction with the form

I'm facing an issue with a form that includes 3 dropdowns getting data from an API. The problem is that the dropdowns do not bind data unless I click on them (blur on any field in the form). Here is my HTML: <form [formGroup]="dropdownsForm&q ...

Picture is not appearing on the screen (Xamarin Forms)

I have displayed all the data on the screen except for the image. Now, I also want to see the image along with the other data like id and name. Below are the code snippets: Changes needed on Page 1 XAML C# code: (Changes on this page?) public partial cl ...

Instead of returning a JSON result, the MVC controller method called from AngularJS is returning the view HTML

Within the HomeController, I have the following method, [HttpGet] public ActionResult GetStudents() { Student std1 = new Student(); List<Student> stdlst = new List<Student>(); std1.Id = 1; ...

Adjust the contents of a DIV depending on which Toggle button is selected

When a user clicks on either "Twin Bed" or "King Bed", the content inside the "demand-message" should change to either "high demand" or "Only ??? rooms left". The ID will remain the same for both buttons due to existing logic. However, the message display ...

Error message "UnrecognizedPropertyException: An unrecognized field error has occurred on an Android device

This is my custom Java class for handling product information. public class Product implements ParentListItem { private String productName; private int productId; private String productImagePath; private String brandName; private int brandId; ...

Language for describing JSON data structures

Imagine my application needing to access data from multiple REST APIs, each supporting JSON responses but varying in the fields used to describe the data. For instance, one API may use time, while another may use timestamp for timestamp data, and similar v ...

How can I securely access and load JSON data from a different domain?

I need to access JSON data from a different domain. The JSON data format is as follows: [ { "siteName": "JQUERY4U", "domainName": "http://www.jquery4u.com", "description": "#1 jQuery Blog for you ...

The error message "Element is not defined (Object.<anonymous>)" is occurring in the context of Intro.js-react, React, Next.js, and Tailwind

Here is a code snippet: import { useState } from 'react'; import { Steps } from 'intro.js-react'; export default function Dashboard() { const [stepEnabled, setStepEnabled] = useState(true); const steps = [ { intro: &apos ...

FirebaseError: Trigger parsing error: Module 'grpc' not found

I'm currently working on setting up an Angular4 application with Server Side Rendering (SSR) using Angular Universal and Firebase Cloud Functions. While the application works smoothly with ng serve, I encountered an issue after building the app and s ...

Assigning a value to an angular object

In my current project with Angular 16, I am executing a query on the database and assigning the returned number to a document number. Data Model export class Document { doc_data: string =""; doc_for: string=""; doc_number: number = 0; doc_ ...

Having trouble converting an array of strings into a JSON ARRAY column in Snowflake

I am encountering an issue with an SQL column in my Snowflake table that is declared as the ARRAY data type. Specifically, when I attempted to perform a COPY INTO from a CSV file where one row contained a value for this column of ["A","B"], it resulted in ...

The challenges of handling dynamic controls and reactive forms in Angular when editing, and ways to effectively update their values

I am currently working on creating an inline dynamic form using reactive forms. I have successfully added a new object and looped it in the DOM, but when I press the edit button, it doesn't work and produces errors in the console. Inside the object, t ...

Graph your data with a stunning Fusioncharts area range graph combined with a sleek

My goal is to create a visual representation of an area range graph with a corresponding mid line. You can view the image below for reference: https://i.sstatic.net/8KDbF.png While I have successfully incorporated the low and high values, I am encounterin ...

The Angular HttpErrorResponse is a class used for handling

I am encountering an issue while attempting to retrieve a user's cart by submitting the username in the request URL. list: PanieDto[] = []; @Input() listform: PanieDto = new PanieDto(); isLoggedIn = false; showAdminBoard = false; showModeratorBoard = ...

Page can be accessed using file_get_contents function but not with cURL

In the process of creating an API endpoint in PHP, a scenario arose where JSON data output from a specific page example.com/stats was causing issues with cURL requests compared to using file_get_contents(). How can I ensure that JSON data served in PHP is ...

What techniques can be employed to dynamically modify Typescript's AST and run it while utilizing ts-node?

Below is my approach in executing a TypeScript file: npx ts-node ./tinker.ts In the file, I am reading and analyzing the Abstract Syntax Tree (AST) of another file named sample.ts, which contains the following line: console.log(123) The goal is to modify ...

Error: The payload in action is not able to be iterated over

Currently, I am delving into the world of ngrx, but I seem to have hit a roadblock. I'm encountering an issue that I can't seem to fix on my own. If anyone out there has some insight and expertise to offer, please help me out. I keep running into ...

Creating an Overlay using a ScrollStrategy in a declarative way

In Short; Can you explain how to utilize a scroll strategy when creating a CdkConnectedOverlay in a declarative manner? Details; The CdkConnectedOverlay is designed as a Directive for simplifying the creation of Overlays through a declarative approach. I ...