Mapping the response from an http.get call to create a new typed object instance in Angular 2

Can anyone help me understand how to map the result from a service call to an object using http.get and Observables in Angular 2?

Please check out this example

In my getPersonWithGetProperty method, I am trying to return an Observable of type PersonWithGetProperty. However, I am unable to access the property fullName. It seems like I need to create a new instance of the class PersonWithGetProperty and map the response to this new object using the class constructor. But how do I achieve this in the getPersonWithGetProperty method?

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

export class PersonWithGetProperty {
  constructor(public firstName: string, public lastName: string){}

  get fullName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

@Injectable()
export class PersonService {
    constructor(private http: Http) {
    }

    getPersonWithGetProperty(): Observable<PersonWithGetProperty> {
        return this.http.get('data/person.json')
         .map((response: Response) => <PersonWithGetProperty>(response.json()));
    }
}

Answer №1

You may encounter issues because you are trying to force the parsed json data to act like a class.

When using <PersonWithGetProperty>, you are not actually creating a new instance of PersonWithGetProperty; instead, you are simply informing the compiler to ignore any warnings as you manipulate the data. To create an actual instance of PersonWithGetProperty, you should use the new keyword for construction.

You are almost there already - just include another map function after parsing the output:

@Injectable()
export class PersonService {
    constructor(private http: Http) {
    }

    getPersonWithGetProperty(): Observable<PersonWithGetProperty> {
        return this.http.get('data/person.json')
         .map((response: Response) => response.json())
         .map(({firstName, lastName}) => new PersonWithGetProperty(firstName, lastName));
    }
}

Edit

In order for this solution to work, ensure that you are utilizing RxJS 5:

import 'rxjs/add/operator/map'

For better compatibility in the future, consider employing the pipe syntax which was introduced in later versions of RxJS 5:

// Either
import {map} from 'rxjs/operators'

return this.http.get('data/person.json').pipe(
  map((response: Response) => response.json()),
  map(({firstName, lastName}) => new PersonWithGetProperty(firstName, lastName))
);

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

Determine the type of the final function within a variable number of nested closures

Imagine you have a function like this: const f = a => b => ... x => { return somevalue } Is there a way to determine the type of just the final function typeof x => { return somevalue } even if we don't know how many closures come before ...

Ways to incorporate a notification feature with an icon or image

I'm looking to create a visually dynamic icon/image similar to mobile device notifications, but primarily for desktop use. This image will be positioned before some text. For instance: https://i.sstatic.net/MHocy.pngSome Text This design features tw ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...

Experiencing a bug in my express application: TypeError - Unable to access properties of undefined (reading 'prototype')

I've encountered the TypeError: Cannot read properties of undefined (reading 'prototype') error in my javascript file. Despite researching online, it seems that many attribute this issue to importing {response} from express, but I am not doi ...

When using Tailwind, be aware that the @screen directive does not automatically generate media queries in

Angular 12 & tailwind ^3.0.12 No media queries are being generated on the screen after compilation based on breakpoints. section { @apply w-full px-6 py-24; @screen sm { @apply py-14; } @screen md { @apply px-0 py-20 max-w-5xl mx-auto; ...

Requesting access with Angular

Hi there, I'm currently getting started with Angular and I am eager to create a login feature. However, I am unsure of how to send a login request. Despite my efforts to find similar inquiries, the only information available pertains to older question ...

Troubleshooting problems with routing for an Angular 5 single page application when serving it from a Lumen 5.2 controller

I am facing an issue with serving an Angular SPA from a single routed Lumen endpoint. While the initial boot of the Angular application works fine when navigating directly to the endpoint, loading any child route of the Angular SPA does not work properly. ...

Conditional Skipping of Lines in Node Line Reader: A Step-by-Step Guide

I am currently in the process of developing a project that involves using a line reader to input credit card numbers into a validator and identifier. If I input 10 numbers from four different credit card companies, I want to filter out the numbers from thr ...

The announcement will not be made as a result of the utilization of a private name

I've been working on transitioning a project to TypeScript, and while most of the setup is done, I'm struggling with the final steps. My goal is to use this TypeScript project in a regular JavaScript project, so I understand that I need to genera ...

Is it possible to define react-router v6 routes within a functional component?

I have developed an application that requires users to log in before accessing it. I attempted to implement it using the following code: import React, {useState} from 'react'; import {Route, Routes} from 'react-router-dom'; import type ...

What is the process for incorporating a standalone custom directive into a non-standalone component in Angular?

Implementing a custom directive in a non-standalone component I have developed a custom structural directive and I would like to use it across multiple components. Everything functions as expected when it is not standalone, but encountering an error when ...

Angular application's HTML Canvas unexpectedly changes to a black color when I begin drawing

Currently, I am developing an Angular application in which users can draw text fields on PDF pages. To achieve this functionality, I have integrated the ng2-pdf-viewer library and created a PDF page component that incorporates an HTML canvas element. Howe ...

I'm facing an issue in Angular 4 where the routing for a child component is

I'm currently working on implementing routing in my Angular app for movies. I've set up a movie component and an edit movie component. The edit movie component is nested within the movie component, as shown in the folder structure below: https: ...

Having trouble with Http.post in Angular4 cli when 'application/json' is set in the header

As a beginner in Angular CLI, I encountered issues with the login API 'http://localhost/appointjobs/index.php/admin_api/index' when using http.post. I was unable to receive post data on the server side (codeigniter/php) when setting 'content ...

NodeJS and Angular2 application experiencing loading issues

Currently, I am diving into the world of Angular2 and thanks to the quick start guide provided on their official documentation, I have successfully set everything up. However, if I plan to work with APIs on the server or host my project in the cloud, it ap ...

What is the process for creating a clickable file upload in Angular?

Currently, I am utilizing the instructions found in this guide to implement a file upload feature in my project. The code provided works perfectly: <input type="file" class="file-input (change)="onFileSelected($event)" #fileUplo ...

Error: Unable to bind to 'ng-class' as it is not a recognized built-in property in Angular 2

I'm attempting to conditionally apply CSS styles to an img attribute based on the value of a boolean variable 'isLoginPage' in Angular 2.0.0-beta.15. Here is the relevant HTML code snippet: <a class="navbar-brand" href="#/"> <i ...

How can we automate the process of assigning the hash(#) in Angular?

Is it possible to automatically assign a unique hash(#) to elements inside an ngFor loop? <div *ngFor="let item of itemsArray; index as i"> <h3 #[item][i]> {{ item }} </h3> </div> I would like the outp ...

What are the limitations of jest and jsdom in supporting contenteditable features?

I am facing an issue with a particular test case: test('get html element content editable value', () => { // arrange const id = 'foo'; document.body.innerHTML = `<div id='${id}' contenteditable="true">1</div ...

Using @material-ui/core/useScrollTrigger in a Next.js application: a step-by-step guide

I have been researching the Material-UI documentation for useScrollTrigger and attempting to implement it in Next.js to replicate the Elevate App Bar. https://material-ui.com/components/app-bar/#usescrolltrigger-options-trigger import React from "react"; ...