"Converting an object array into my own custom type array: A step-by

I have a class:

export class    Items {
      id: string;
      itemName: string;
    }

Previously, when using Angular version less than 4.3, I had this method:

getItems(): Observable<Items[]> {
    return this.http.get('api-url-here/items')
        .map((data: Response) => {
            return data.json()
                .map((item: any) => {
                    return {
                    id: item.id,
                    itemName: item.itemName
                };
        });
    })
}

After upgrading to Angular version 4.3 or above, the method was updated to:

getItems(): Observable<Items[]> {
    return this.http.get<Items[]>('api-url-here/items')
        .map((data: any) => {
            return data
                .map((item: any) => {
                    return {
                    id: item.id,
                    itemName: item.itemName
                };
        });
    })
}

The response from the API now looks like this:

[
 {"id":1,"itemName": "item name" }
]

https://i.sstatic.net/WmLPn.png

Looking at the updated code examples above, such double mapping is required to shape the data into the desired type. Is there a more efficient approach to accomplish this using Angular 4.3 or newer versions?

Answer №1

If you are utilizing typed responses with the new HttpClientModule, your result is already parsed in the first map.

getStuff(): Observable<Stuff[]> {
  return this.http.get<Stuff[]>('api-url-here/stuff');
}

This should work. Next,

SomeStaffService.getStuff().subscribe(staff => console.log(staff));

Update:

In this scenario, you have two options to handle errors. You can handle them outside of your service

SomeStaffService.getStuff().subscribe(
  staff => console.log(staff),
  (err: HttpErrorResponse) => {
    if (err.error instanceof Error) {
      console.log("Client-side error occurred.");
    } else {
      console.log("Server-side error occurred.");
    }
  }
);

Alternatively, you can subscribe directly in your service and catch the error there. Please see the documentation for more information.

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

"Convert a date string to a date object using the verbose moment date

I utilized the materialize datepicker to select a date in French format. Now I need to convert this formatted date back to a date object for use in my API. Here's how I attempted to revert the date to a standard format: moment("dimanche 30 juillet 20 ...

The npm run scripts seem to be malfunctioning, but when the scripts are executed individually,

I've encountered an issue while attempting to execute scripts with NPM. Despite my efforts, I consistently end up with errors. Package.json "scripts": { "ng": "ng", "start": "ng serve --open", ...

Definition of TypeScript type representing the value of a key within an object

As I delve into defining custom typings for a navigation library using TypeScript, one challenge that has me stumped is creating a navigate function. This function needs to take the Screen's name as the first argument and the Screen's properties ...

Retrieve the stored information from a variable

Can anyone help me with a coding issue I'm facing? I have a constant called data, which contains two values - prediction and probability. What is the best way to access and retrieve both values? type ML = { prediction: string; probability: num ...

The message shown on items.map stating that parameter 'item' is implicitly assigned the type 'any'

Currently, I am delving into the world of Ionic React with Typescript by developing a basic app for personal use. My current challenge involves dynamically populating an IonSegment from an array. Here is the relevant code snippet: const [items, setItems] ...

Issues encountered when attempting to use @rollup/plugin-json in conjunction with typescript

I have been encountering an issue with my appsettings.json file. Despite it being validated by jsonlint.com, and having the tsconfig resolveJsonModule option set to true, I am facing difficulties while importing @rollup/plugin-json. I have experimented wit ...

Is it possible for node modules to access and utilize protractor parameters?

Is it feasible for a node module to access a protractor parameter? I am in need of defining a parameter in my protractor conf.js file and then running a specific section of the shared node module js file across 5 projects. For instance, in my conf.js: ...

Is there a way for me to control the permissions granted to jhipster's authorities?

In the process of developing a web application with JHipster code generator, I have extended the pre-existing roles to a total of 5: ROLE_USER, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_PRESIDENT, ROLE_VICE_PRESIDENT I am now seeking guidance on how to manage per ...

Can you explain the significance of this code snippet 'true <=> false'?

Today I came across this piece of code: true <=> false. I'm a bit confused by it and don't really understand how it works. If anyone could shed some light on this expression for me, I would greatly appreciate it. For reference, this code ...

Unexpected error: Angular 4 TypeScript validation issue - An object literal can only define recognized properties

excellent customer service import {Account} from '../models/Account'; export class AccountingService { domain: string = "http://localhost:3000/api"; constructor(private http: HttpClient) { } getAccounts(){ return this.http.get&l ...

Why did the homepage load faster than the app.component.ts file?

I am facing an issue where the homepage is loading before app.component.ts, causing problems with certain providers not working properly due to import processes not being fully completed. Despite trying to lazy load the homepage, the console.log still sho ...

Angular App Failing to Validate Session Cookie 'sessionId' in AuthGuard

Encountering a perplexing issue with my Angular application where the AuthGuard fails to recognize a session cookie named 'sessionId' correctly. I have successfully implemented user authentication, and the expected behavior is for users to be dir ...

Retrieving the attribute key from a dynamically typed object

Having this specific interface structure: interface test { [key: string]: string } along with an object defined as follows: const obj: test ={ name: 'mda', telephone: '1234' } Attempting to utilize this object in a variab ...

Adding a Third-Party JavaScript Plugin to Angular 7

I've been attempting to integrate the read-excel-file JavaScript plugin into my Angular 7 project. Despite following all the methods recommended on various websites, I have yet to succeed. Could anyone provide a better solution? declare var readXlsx ...

Properly specifying the data type for a generic type variable within a function in TypeScript

As I work on my express project, I am currently coding a function called route. const morph = (params: Function[]) => (req: Request) => params.map(f => f(req)) const applyTransformers = (transformers: Function[]) => (response: any) => { ...

Running headless Chrome with Protractor on Windows platform is presenting difficulties

While there is a wealth of documentation available on headless chrome automated testing, information specifically for Windows users seems to be lacking. Furthermore, details on utilizing headless chrome for end-to-end automated testing in a fully develope ...

I keep encountering a syntax error every time I attempt to run the yarn start command

Upon attempting to execute yarn start, an error appeared in the command line indicating a syntax error. I have already attempted updates on both node and yarn. $ node --max_old_space_size=8192 ./node_modules/.bin/ng serve -H 0.0.0.0 --disable-host-check ...

Obtaining context from a higher order component in the constructor of a child component: tips and tricks

In order to gain access to context throughout the application, I've implemented the following context provider: import React, { Component, useContext } from 'react'; import { appInitialization, Context } from "@microsoft/teams-js"; ...

Issue with displaying labels in ChartJS plugin on Ionic 3 platform

Currently, I am using Ionic 3 and have implemented a bar chart in my project. However, I am facing an issue where the data labels are not being displayed next to the bars on the chart. This is similar to the problem discussed in this question how to displa ...

Tips for avoiding dual API calls in Angular

How can I avoid making two API calls in Angular? I have a function that is called twice in ngOnInit, but I want it to only execute once when the id changes from the URL parameter. However, both functions are being invoked when the page is loaded for th ...