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

Issue with NzPicker (nz-year-picker) due to absence of animation

Whenever I try to use the NzPicker, an error pops up on my screen. I'm encountering the same issue when adding the NzNoanimationModule. Is there a way to resolve this problem? <nz-year-picker (ngModelChange)="onChange($event)" nzPlaceHolder="sel ...

Risky assignment of an 'any' value" encountered while implementing react-transition-group in TypeScript

Encountering @typescript-eslint errors while implementing the Transition component from react-transition-group. Implemented the official React Transition Group example for JS in a TypeScript + ESLint project, resulting in the error message: Unsafe assignm ...

Ensuring the type of a specific key in an object

Seeking a more stringent approach regarding object keys in TypeScript. type UnionType = '1' | '2' | '3' type TypeGuardedObject = { [key in UnionType]: number } const exampleObject: TypeGuardedObject = { '1': 1, ...

Encountering difficulties with implementing reactive forms in an Ionic Angular 7 project as the app.module.ts file appears to be missing

Currently, I am working on a project using Ionic Angular 7 and I am facing some challenges with implementing reactive forms. Since app.module.ts is not in Ionic Angular 7 anymore, I tried to search for solutions online. Unfortunately, when I followed the i ...

Troubleshooting Angular modal fade not functioning

I am facing an issue while trying to display a component called "Login", which belongs to the class "modal fade", from another component named "navbar". Despite my attempts to trigger it by calling data-bs-toggle="modal" data-bs-target="#LoginModal" from t ...

Style will be applied to Angular2 when the object's ID exceeds 100

I am working with object markers that have different Id's assigned to them. Now, I am trying to apply additional styling when the id > 100. Check out the code snippet below: <span *ngIf="result.object.reference > 100" class="tooltip-data"&g ...

There was an issue retrieving the metadata for the bootstrap package using the git+ssh protocol

While attempting to install angular devkit and other dependencies using npm install, I encountered the following error message: Could not retrieve metadata for bootstrap@git+ssh://example@example.com/gios/Web-Standards-Bootstrap.git#05a343dddce91dd157702 ...

Using the spread operator in Typescript with an object that contains methods

Within my Angular project, I am faced with an object that includes a type and status field where the status can change depending on the type. While some might argue that this is not the best design practice, it is how things are currently structured in my ...

Encountering an error while compiling the Angular 8 app: "expected ':' but got error TS1005"

As I work on developing an Angular 8 application through a tutorial, I find myself facing a challenge in my header component. Specifically, I am looking to display the email address of the currently logged-in user within this component. The code snippet fr ...

Guide on uploading an image to Azure Blob Storage using v10 SDK

Currently, I am attempting to upload an image to the Blob Storage in Microsoft Azure using SDK V10 within an Angular framework. The code snippet below demonstrates how I establish a connection to the Storage and retrieve the names of all containers: // E ...

Eliminate Elements from Array - Angular Four

I am currently developing a basic to-do app using Angular4. The setup of the app is structured as follows: Form Component: Responsible for adding items to the to-do list Item Component: Represents individual to-do items App Component: Contains a *ngFo ...

How to include an image in a file type using Angular 2 and TypeScript

Is it possible to assign an image to a file type variable in Angular 2? I attempted the following approach: private file:File; setImage(){ this.file = "../assets/image/image.jpg" } Unfortunately, this method did not succeed. ...

Refreshing the cache in SWR, but the user interface remains unchanged inexplicably - SWR hook in Next.js with TypeScript

I am currently working on a project that resembles Facebook, and I am facing an issue with the like button functionality. Whenever I press the like button, I expect to see the change immediately, but unfortunately, SWR only updates after a delay of 4-8 sec ...

Dealing with Scoping Problems in a Typescript d3 Update Tutorial

I'm facing challenges trying to implement the provided bl.ocks example in Typescript (using Angular). This is my implementation in TypeScript: StackBlitz Could anyone offer insights on what might be causing the issues I'm encountering? My initi ...

What is the process of incorporating a function into an object?

My current object has: public functions = { chosenYearHandler: null, chosenMonthHandler: null }; There is a method within the object: public chosenMonthHandler(normalizedYear: any) { this.form.controls["date"].setValue(normalizedYear); ...

MediaRecorder is not compatible with Protractor unit tests in Angular

Currently working on an Angular 11 project that includes unit tests. Just introduced a MediaRecorder into the project, but now none of the tests are functioning properly. The test compilation is throwing this exception: error TS2304: Cannot find name &apos ...

Issue with Http Interceptor in Angular 4: Error message - next.handle(...).do is not a valid function

Initially, the HTTPInterceptor I created was functioning well for handling HTTP errors. However, after performing a git pull and npm install, it seems to have encountered issues. The following is the code snippet: import {Injectable} from '@angular/ ...

Communicating Between Children Components in Angular 2

Is there a way to achieve Child-Child communication in Angular2? While the Angular2 Documentation offers solutions for Parent-Child communication, I am curious about how children components nested within a parent can interact with each other. Can one child ...

Plugin for listing contacts using Nativescript

I am currently developing a contact list application using NativeScript with Angular. I have integrated the nativescript-contacts plugin into my project and everything is working smoothly on the iOS emulator on macOS High Sierra. Following the documentatio ...

The Microsoft.Azure.WebJobs.Script encountered an issue while attempting to cast an object of type 'System.String' to type 'Microsoft.AspNetCore.Http.HttpRequest' during the return process

I recently encountered an issue with my Azure Function written in JS that is triggered by the Service Bus and generates files to Blob Storage. When attempting to return an HTTP result, I received the following error message: System.Private.CoreLib: Except ...