Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is:

The returned data follows this structure:

{"status":"success","data":[{"id":"1","employee_name":"Tiger Nixon","employee_salary":"320800","employee_age":"61","profile_image":""},{"id":"2","employee_name":"Garrett Winters","employee_salary":"170750","employee_age":"63","profile_image":""} ...

Displayed below is the TypeScript code segment:

constructor(private http: HttpClient) { }
configUrl = 'http://dummy.restapiexample.com/api/v1/employees';
getEmployees() {
var x = this.http.get<Employee[]>('http://dummy.restapiexample.com/api/v1/employees').pipe(map(res => res['data']));
alert(JSON.stringify(x));
}

This represents the Employee class utilized:

export class Employee {
id: any;
employee_name: any;
employee_salary: any;
employee_age: any;
profile_image: any;
}

According to my exploration, one should apply pipe(map(res =>res['data']), however, it isn't functioning correctly in my case. Any assistance in comprehending what might be incorrect with the aforementioned code would be greatly appreciated.

Answer №1

In the latest version of HttpClient, data mapping is not required. This eliminates the need for a pipe operator in this scenario. Additionally, in order to actually receive the data, you must subscribe.

Take a look at the example below:

constructor(private http: HttpClient) { }
configUrl = 'http://dummy.restapiexample.com/api/v1/employees';
getEmployees() {
var x = this.http.get<Employee[]>('http://dummy.restapiexample.com/api/v1/employees');
return x;
//alert(JSON.stringify(x)); This won't work because you need to first subscribe to the observable.
}

// Let's assume there is a main function that calls your getEmployees function. Here is what you should do

main() {
  this.getEmployees().subscribe(x => {
    alert(JSON.stringify(x));
  });
}

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

Hide the navigation menu when a page link is selected

Within my Angular 8 application, a fixed navigation bar is positioned at the top of the screen. Upon hovering over a dropdown nav link, a menu will appear for the user to explore. However, when a user clicks on one of these menu links, Angular Routing is ...

How to handle form-data in NestJS Guards?

I've been trying to access form-data in my NestJS Guards, but I'm experiencing some difficulties. Despite following the tutorial provided here, I am unable to see the request body for my form-data input within the Guard itself. However, once I ac ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

Tips for utilizing an adaptive design with Angular

I am working on designing a page that allows for scrolling if needed. On each section of the page, I will be incorporating specific components with unique colors to enhance the layout. However, my current HTML code is not producing the desired result as sh ...

Dispatch a websocket communication from a synchronous function and retrieve the information within the function itself

I am currently working on an Angular project and need guidance on the most effective approach to implement the following. The requirement is: To retrieve an image from the cache if available, otherwise fetch it from a web socket server. I have managed ...

What is the method for setting autofocus to the first input element within a loop?

I am currently working on a loop to display inputs, and I would like to be able to add focus to the first input element when it is clicked. Does anyone have any suggestions on how I can select that first element and set autofocus on it? ...

Error message "Undefined is not a constructor" can occur when using Ionic2 with Karma and Jasmine

I'm facing a challenge while trying to create tests for an Ionic2 App using Karma + Jasmine. I encountered a runtime error and, given my lack of experience, I'm having trouble pinpointing the actual issue. Here is my setup: test.ts This file con ...

Change classes of sibling elements using Angular 2

Imagine you have the following code snippet: <div id="parent"> <div class="child"> <div class="child"> <div class="child"> </div> I am looking to automatically assign the class active to the first child element. ...

Injecting dynamic templates in Angular 7

Let me simplify my issue: I am currently using NgxDatatable to display a CRUD table. I have a base component named CrudComponent, which manages all CRUD operations. This component was designed to be extended for all basic entities. The challenge I am en ...

Storing dates using Angular 2 and JSON for efficient data management

I've encountered a challenging issue with my Angular 2 application. I'm attempting to organize my API (MongoDB) in such a way that each new "post" added by the admin can be retrieved by date (not time) on the front end. Here's an example of ...

Nested loop with Angular and Bootstrap Modal

I am trying to implement a Modal in Angular to display the details of a row in a table with matching IDs, but I'm encountering an issue where only the data from the first row is shown when I open the Modal. The other rows do not seem to work correctly ...

Angular Material Rotate Ink Bar to Vertical Orientation

After wanting to change the orientation of Angular Material's Tab Component to vertical, I visited this page (Tabs) and experimented with the CSS. By making the necessary adjustments, I successfully displayed the tabs vertically using the following CS ...

Firebase V9: Uploading and Updating Documents

I am currently working on updating messages in Firebare for a chat functionality using the method below: markConversationAsSeen(conversationId: string, email: string) { const messages = collection(this.firestore, 'messages'); const q = q ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

Angular 4 enum string mapping reversed

Here is an example of a string enum: export enum TokenLength { SIX = '6', EIGHT = '8', } I am trying to retrieve the string value 'SIX' or 'EIGHT' by reverse mapping this enum. I have attempted various methods: ...

One way to display a table is by populating it with data from an API. If the table does

Within my Angular 6 application, there exists a table that displays data fetched from a web api. Additionally, I have incorporated some ngIf containers. One of these containers is programmed to exhibit a message in case the web api data turns out to be emp ...

Accessing files from various directories within my project

I'm working on a project with 2 sources and I need to import a file from MyProject into nest-project-payment. Can you please guide me on how to do this? Here is the current file structure of my project: https://i.stack.imgur.com/KGKnp.png I attempt ...

Tips for accessing an item from a separate TypeScript document (knockout.js)

In the scenario where I need to utilize an object from another TypeScript file, specifically when I have an API response in one.ts that I want to use in two.ts. I attempted exporting and importing components but encountered difficulties. This code snippe ...

Develop a fresh category inspired by the properties of objects

Let's tackle the challenge of constructing a new type in Typescript based on an descriptive object named schema, which contains all the requirements expressed within it. Here is my proposed solution: type ConfigParameter<IdType, ValueType> = Re ...

Unexpected Issue: Angular 12 Encounters JIT Compiler Unavailability

Lately, I've been encountering a persistent issue with an error message: Uncaught Error: JIT compiler unavailable. Ever since I upgraded from Angular version 8 to 12, whenever I run the ng build --prod --output-path = dist command and build Angular, e ...