Using Angular's Http Get to retrieve information from a json file

I need to extract only the 'firstName' values from the JSON data below using an Angular HttpGet method.

[
    {
    "id": "65664546",
    "name": "Employee 1",
    "contacts":
        {
            "id": "56546564",
            "firstName": "James",
            "lastName": "Carter",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6506041711001754555425020a0a0209004b060a08">[email protected]</a>"
        }
    },
    {
    "id": "65664547",
    "name": "Employee 2",
    "contacts":
        {
            "id": "56546565",
            "firstName": "Steve",
            "lastName": "Smith",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="46352b2f322e3577767706212929212a236825292b">[email protected]</a>"
        }
    },
    {
    "id": "65664548",
    "name": "Employee 3",
    "contacts":
        {
            "id": "56546566",
            "firstName": "Anna",
            "lastName": "Marcus",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6805091a0b1d1b595859280f07070f040d460b0705">[email protected]</a>"
        }
    }
    ]

Can you provide guidance on how the Httpget method and subscribe method for this extraction should be written?

Answer №1

To achieve this, you can utilize the provided code snippet:

constructor(private http: HttpClient) { }

ngOnInit() {

   this.http.get("./assets/mydata.json")   // specify the path to your JSON file
       .pipe(
          map(emp => emp.map(e => e.contacts.firstName))
       ) // extract the first names from the "map" array in the JSON
       .subscribe(res => console.log(res));
}

Answer №2

One immediate question arises - are you in control of the backend generating that JSON data? If so, you might consider creating a separate action method (perhaps following Microsoft's terminology) that specifically provides a list of strings containing only the firstName information. I won't delve into specific examples as I am unsure about the backend technologies you are using.

Alternatively, if you do not have control over the backend, there are still options available on your end.

One option is to subscribe to the HTTP stream and then map the results:

this.http.get("whatever").subscribe(res => res.map(x => x.firstName));

This is just an illustration and the actual application structure may vary. Subscription could occur within services, components, or utilize the async pipe.

Another approach would be to follow Nicholas K's recommendation and employ reactive programming with pipe(map(...)). I will refrain from reiterating his answer for clarity.

At present, I cannot think of any other alternatives.

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

Fetching JSON data using Promise.all results in an empty response

I'm facing an issue in my code where I am trying to fetch data from two different JSON files and then return them as arrays. Even after implementing the solution below, it doesn't seem to be working as expected. Can someone guide me on how I can ...

The initialization of Angular 5 services occurs prior to the completion of APP_INITIALIZER

I am currently in the process of upgrading my AngularJS 1.6 application to Angular 5, and I am facing an issue where my services are getting initialized before the APP_INITIALIZER is completed. Background: I need to fetch the application configuration u ...

Modify multiple elements in a nested array by utilizing the $set and $push operators

Here is an example of the Workspace document that needs box positions updated when dragged and dropped on the front end. { "_id": ObjectId("5eaa9b7c87e99ef2430a320b"), "logo": { "url": ".../../../assets/logo/dsdsds.png", "name": "testUpload" }, "n ...

Set up the user django with standard configuration values

I'm currently working with Django and Angular 2, trying to create a user with default values, but it's not happening as expected... Model class Settings(models.Model): user = models.ForeignKey('auth.User', related_name='setti ...

Exploring the World of Angular: Abstracts and Data Transformations

Facing a perplexing issue with a component that is based on an abstract class, or at least that's my assumption. There are multiple sibling components rendered using *ngFor based on an array length. These siblings, derived from an abstract class, rec ...

Guidelines for sorting a dataset according to the current UserID using angular2

Hello, I am working with a dataset where I need to filter the data based on my userID and display only that specific information in a list. Can someone assist me with this? TS: getDicomList() { this.service.getDicomList(params) .subscribe((res) ...

Why is TypeScript giving an error about an undefined object key, even though the key was assigned a value in the previous command?

type MaybeThereIsAValue = { [p: string]: string | undefined } ... let bar: MaybeThereIsAValue = {}; const key = "carpe"; bar[key] = "diem"; const why = bar[key]; // why is string | undefined I am confused as to why why is showing ...

TypeScript's attempt to replicate Scala's underscore feature has been implemented, but it proves to

I've been working on a personal project for the past 2 years trying to implement Scala's underscore in TypeScript, but haven't been successful. Here is my attempted implementation and its effect. The only thing that I really care about typi ...

What is the best way to rid ourselves of unwanted values?

In the laravel-vue-boilerplate package, there is a User CRUD feature. I duplicated this functionality to create an Item CRUD by making some changes and adjustments. Everything is working fine except for one issue: after editing an item, when trying to add ...

Where is the best place to import styles in NextJS?

I have an existing project with a file importing the following function import theme from 'src/configs/theme' However, when I created a new Next.js project and replicated the same folder structure and imported the same function, it is showing "m ...

I want to remove an object from my Django Rest Framework (DRF) database using Angular 13

After receiving the id that needs to be deleted, I noticed that the last line of code in service.ts for the delete method is not being executed. The files and code snippets I utilized are: COMPONENT.HTML <li *ngFor="let source of sources$ | async ...

Issue with displaying first label on X axis in Bar chart using Angular and ChartJS

I'm working on creating a bar chart using ChartJS and Angular. My goal is to group the X-axis values to display only the year. https://i.stack.imgur.com/xqF21.png However, I've noticed that the first year is missing each time. In the example pr ...

Troubleshooting the lack of communication between multiple Subscribers in RxJS/Angular when sharing one observable

For a project using Angular 4, I am implementing an HTTP call to retrieve data from the backend. To optimize performance, I cache the data once it is fetched so that subsequent requests do not require additional API calls. getApplication(): Observable< ...

Encountering an issue while running the ng build --prod command in Angular

I ran into an issue while trying to execute the command ng build --prod in Angular. I've completed my small project and now need to generate the necessary files for uploading to my hosting provider. ERROR - ANGULAR CLI C:\Users\Johan Cor ...

Issues with launching project following updates to Angular-cli

After updating npm, node, and angular-cli to the latest versions, I encountered an issue when running the ng serve command in my existing project. ERROR in ./src/main.ts Module build failed: TypeError: Cannot read property 'newLine' of undefined ...

Utilizing Checkboxes for Filtering Mat-Table Data in Angular 8

I've been attempting to implement checkbox filtering for a table, but none of my attempts have been successful so far. Here is a snippet of my table structure: <mat-table [dataSource]="dataSource" [hidden]="!show" matSort > <!-- Locat ...

The error message `Error [ERR_REQUIRE_ESM]: require() of ES Module` is triggered when attempting to call the old

I've been attempting to integrate with the Unsplash API, but I'm encountering an issue. When I try to execute the script using ts-node like this: ts-node unsplash.ts I receive the following error: C:\Users\USER\AppData\Roamin ...

Is it possible to send prop as an object property in a TypeScript-based React component?

I am struggling with a persistent issue: export const LIST_OF_TYPES = { TYPE1: 'type1', TYPE2: 'type2', }; In the element, I specify the classification as such: export type IComponentCategoryType = 'type1' | 'type2&a ...

What sets template-driven and reactive forms apart in practice?

Exploring the Angular2 new Forms API has revealed two distinct approaches to forms: Template driven and reactive (model-driven) forms. I am curious about the real-world differences between these two methods, beyond just syntax. Which approach is more adva ...

Angular nested innerHTML not evaluating ternary operator

Here is a code snippet that I am struggling with: {{ Name && Name.length > 20 ? (Name | slice: 0:20) + "..." : Name }} The above code works fine when used inside a div, but when I try to use it within innerHTML, I encounter a syntax e ...