Why isn't the http.get response being properly typed?

Recognizing a common pattern in Angular and TypeScript:

import { Component } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@common/http';
import { Observable } from 'rxjs';



@Component({
    selector: 'some-selector'
})
class someComponent{

    someObject: someClass;
    someSum: number;
    someError: string;
    
    constructor(private _someService: SomeService) 
    {}
    
    getSomeObject(): void {
        this._someService.getSomeObject().subscribe<someClass>({
            next: results => {
                this.someObject = results;
                this.someSum = this.someObject.sum();
            },
            error: err => this.someError = err,
            complete: () => {}
        )
    }
}



class SomeService {
    constructor(private _http: HttpClient) 
    {}

    getSomeObject(): Observable<someClass> {
        return this._http.get<someClass>("");
    }
}



class someClass {
    prop_1:number;
    prop_2:number;
    sum():number{
        return this.prop_1 + this.prop_2
    }
}

Omitting error handling for simplicity. Despite the code seemingly set up to map HTTP responses to specified classes, an error is encountered during debugging with Chrome's F12 inspector:

core.js:4081 ERROR TypeError: _this.someObject.someSum is not a function

The issue arises at "this.someSum = someObject.sum();"

What additional steps are needed for proper deserialization of http.get results to match their specified object type?

Answer №1

Seemingly, it's not as straightforward. Check out the section titled "Requesting a typed response" on https://angular.io/guide/http

By specifying the response type, you are informing TypeScript to treat your response as matching that type. This is a check done at compile time and does not ensure that the server will actually return an object of the specified type. It is the responsibility of the server to make sure that the response aligns with the expected type defined in the API.

...and then...

To define the type of the response object, create an interface with the necessary properties. Opt for an interface over a class because the response is a plain object that cannot be directly converted into an instance of a class.

...and finally,

When passing an interface as a type parameter to the HttpClient.get() method, utilize the RxJS map operator to modify the response data according to the UI requirements. Subsequently, feed the modified data to the async pipe.

It seems like I'll need to manually and explicitly convert the incoming object into the desired interface or class (with RxJS map being one approach to achieve this).

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

Execute function when button is not active

Within my Angular 2 application, I have a form along with the following code snippet that relates to the button responsible for submitting the form. <button (mouseover)="showMesageValidation()" class="edm-button" type="submit" [disabled]="!f.valid"> ...

What is the best way to compress a file for transfer to a server using gzip?

While attempting to upload a file and send it to the server via a REST API, I am looking for a reliable method to gzip the file. Unfortunately, there is limited documentation available on this topic. Can anyone suggest the most effective approach to achiev ...

What is the best way to adjust the bootstrap column size using variables and decide when to insert a new row dynamically?

I am struggling to dynamically change the number of columns in a row based on the already sorted array. I want the layout to look like the example at the bottom, with Comedies spanning two rows, Action spanning three, and Horror only one row. However, I ca ...

Internet Explorer 11 fails to interpret the attribute attr.xlink:href

I am a beginner in Angular 2 and I'm working on creating an icon component. The code I have below works perfectly in Chrome and Firefox, but unfortunately, it's not functioning in Internet Explorer 11. Here is what my component looks like: @Com ...

What is the significance of a React Functional Component returning JSX.IntrinsicElements?

I stumbled upon this React functional component in a particular documentation import React, { useState, useEffect } from 'react'; import { fabric } from 'fabric'; interface ITextProps { id: string; options: fabric.ITextboxOptions; ...

Discovering different types of navigation in React Navigation using navigationRef

I'm currently working on adding types to my TypeScript version of this function, but I'm facing some difficulties with it. Perusing the React Navigation documentation: // RootNavigation.js import { createNavigationContainerRef } from '@rea ...

Issue with Angular 4 Bootstrap Carousel

I encountered a console error that I couldn't resolve while working on my project. The technology stack involves Angular 4 and Bootstrap. Unfortunately, my frontend developer is unavailable this weekend, and I'm unsure if there are any missing d ...

Activate OnChanges by modifying a property within the object that is bound to the data

Is there a way to make ngOnChanges() fire when a property of a data-bound object changes without needing to assign a new object to the property? // Inside the component @Input() myObj: ObjType; // Component code... The above scenario does not trigger the ...

Unable to execute a POST request using the HTTPParams Object

I'm facing a challenge as a newcomer to Angular when it comes to fetching data from a server using the Angular httpClient and HttpParams. While the uri specification works, I am striving for an alternative solution using the HttpParams Object. I&apo ...

Angular 18 mysteriously generating a fake routing error, even though the routes were functioning perfectly before

Issue: I've been working on integrating a login component with Google authentication in my Angular application. The user information is retrieved upon successful authentication, a token is generated, and then sent to the backend for further processing ...

Encountering a Problem with NPM Installation for Angular 6

I am currently facing an issue with my Angular 6 project. Whenever I try to execute it, I encounter the following error: Could not find module "@angular-devkit/build-angular" from "C:\\Users\\fernando.cavalcante\\Desktop&bsol ...

The typed union type FormGroup in Angular stands out for its versatility and robustness

Within my application, users select a value from a dropdown menu to determine which type of FormGroup should be utilized. These formGroups serve as "additional information" based on the selection made. I am currently working with three distinct types of f ...

Guide to vertically aligning text in an overlay using CSS within Angular 2

I currently have an overlay on my page that displays a spinner (an Angular material component) and accompanying text. This overlay covers the entire page and prevents clicking on elements below it. The spinner is positioned in the center of the page, and ...

Combining two objects by aligning their keys in JavaScript

I have two simple objects that look like this. var obj1 = { "data": { "Category": "OUTFLOWS", "Opening": 3213.11, "Mar16": 3213.12, "Apr16": 3148.13, "May16": 3148.14, "Jun16" ...

Focusing on an input element in Angular2+

How do I set focus on an input element? Not with AngularDart, but similar to the approach shown in this question: <input type="text" [(ngModel)]="title" [focus] /> //or <input type="text" [(ngModel)]="title" autofocus /> Does Angular2 provi ...

Instructions for creating a button in Angular 6 that will only allow submission of .json files upon clicking

I am in the process of developing a new section in the app dedicated to imports. I am looking to add an import button that specifically allows for Json files only. My experience lies mostly in backend development, but I am delving into Angular 6 for this ...

Typescript indicates that an object may be potentially null

I've hit a roadblock where I keep getting warnings that the objects might be null. After searching online and on StackOverflow, I've tried numerous solutions with no luck. My goal is to insert the text "test" into the HTML elements using their ID ...

Web-based API for authentication system using Ionic framework and token-based login

https://i.sstatic.net/OzKkI.pngI am developing a photo-sharing app that requires a login system. However, when attempting to log in, an error occurs stating that the value is not found. I am able to retrieve the value in services but struggling to get the ...

Can a provider in Angular 2/4 be initialized only after a promise has been resolved?

Within my provider's constructor, I have the following code snippet: constructor( public http: Http ) { this.http.get("api.php").toPromise().then(res=>this.res = res.json()); } However, my goal is to restrict access to this provider u ...

"ng-new" is not currently present in the "@schematics/angular" collection

After removing npm and node, as well as homebrew, I restored them by downloading from the online site. I also installed the Angular cli using npm. Navigating to my desktop in the terminal, I entered: ng new mag-board to initiate my angular project. Howev ...