Type information is lost when toString() is returned after traveling through HttpClient on Angular 10

I created a Foobar class with a custom toString() method that works perfectly fine in most cases, except when the Foobar object is returned from a REST call. The following code snippet and its output demonstrate this issue: FOOBAR-1 behaves as expected, while FOOBAR-2 does not return a string but an Object instead. Why is this happening? On the other hand, FOOBAR-3 returns the expected result, indicating that it recognizes it as a Foobar object.

app.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, ViewChild } from '@angular/core';
import { Foobar } from './foobar';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private http: HttpClient) {
  }

  ngAfterViewInit() {

    console.log("FOOBAR-1 IS " + new Foobar().toString());
    const remoteUrl:string = 'http://localhost:8080/foobar';
    let observable:Observable<Foobar> =  this.http.get<Foobar>(encodeURI(remoteUrl));  
    observable.subscribe(
      (foobar: Foobar) => {
        console.log("FOOBAR-2 IS "+foobar.toString());
        console.log("FOOBAR-3 IS "+foobar.foo);
      }
    );
  }
}

foobar.ts

export class Foobar {

    foo:string ='bar';

    toString(): string {
        return this.foo;
    };
}

Console output:

app.component.ts:18 FOOBAR-1 IS bar
app.component.ts:23 FOOBAR-2 IS [object Object]
app.component.ts:24 FOOBAR-3 IS bar

Why does the toString() method behave unexpectedly on objects returned from HttpClient requests? What exactly is causing this behavior?

Answer №1

When making an HTTP call, the response is usually in the form of a string, often containing JSON like

'{"foo": "bar"}'
. This JSON string can be converted into a JavaScript object, such as { foo: 'bar' }, which can then be used in your code.

const foobar = { foo: 'bar' };
console.log("FOOBAR-2 IS " + foobar.toString());
console.log("FOOBAR-3 IS " + foobar.foo);

It's important to note that this object is not an instance of class Foobar, as it has not been instantiated in that way. The type annotations simply indicate how the object should behave and do not change its actual type.

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

"Debating Angular: Comparing the Use of Getters and Methods in

To prevent cluttering the *ngIf directive with logic directly in the template. <div *ngIf="a === 3 && b === 'foo'"></div> I typically create a custom method like this: public isOk(): boolean { return a === 3 & ...

A method to trigger the opening of a div tag when a button is clicked using Vue.js

<div class="input-wrapper"> <div class="mobile-icon"></div> <input class="input-section label-set" type="text" v-model.trim="$v.mobile.$model" :class="{'is-invalid': ...

Encountering TypeError in ReactJs due to undefined this.props.users.items

I am currently building a ReactJs application using the GitHub Api. I encountered an error stating this.props.users.items is undefined. The API link I am using is , where there is an object containing an array of items. How can I access this API to retriev ...

Filtering nested objects in JavaScript based on a specific property value

I have a list of objects nested in JavaScript and I need to filter them based on a specific search string and property value. My goal is to extract only the categories with children that are not hidden and contain at least one profile with a name matching ...

Ways to effectively link up Ajax/JavaScript with the back end

I have recently developed a PHP class that enables my users to easily manage their accounts by utilizing functions such as createAccount, updateAccount, and more. Typically, I create an 'interface' script for each function where I initiate the c ...

How come the useEffect hook is causing re-rendering on every page instead of just the desired endpoint?

I am a novice attempting to retrieve data from a database and display it on the front-end using Axios, ReactJS, and TypeScript. My intention is for the data to be rendered specifically on localhost:3000/api/v1/getAll, but currently, it is rendering on all ...

Using absolute imports to resolve modules in TypeScript and Next.js

When I import functions from files using absolute imports, I keep encountering errors that I have been trying to resolve. The errors manifest in a certain way, as shown here: https://i.sstatic.net/J7Ai1.png Despite the errors, the functions are successful ...

Maximizing efficiency in processing multiple requests simultaneously using ajaxSetup's data

I need to enhance an existing ajax request within our CMS by adding additional data. Specifically, I am working with a media library that loads image data (json), and I want to incorporate more images from an external source. var promise_waiting = []; jQu ...

The ScriptManager.RegisterStartupScript function does not execute a second time when used inside an UpdatePanel

My aspx page <span> <asp:UpdatePanel ID="upPlayBtn" runat="server" > <ContentTemplate> <asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" /> </ContentTemplate> </asp:UpdatePanel> </span> ...

Achieving left alignment for Material-UI Radio buttons: Float them left

Click here to view the demo https://i.stack.imgur.com/Yt4ya.png Check out the demo above to see the code in action. I'm currently struggling to align the radio buttons horizontally, wondering if there's an easier way to achieve this using Mater ...

Generate a Vue project using the vue-cli-service build command, but be sure to include the necessary period in

After completing my Vue project, I encountered an issue when running the script 'npm run build' (vue-cli-service build). The output files were generated as expected, but the paths to all js and css files in the index.html file were incorrect. For ...

A guide to efficiently loading all files within subdirectories via rollup, no need for those pesky require statements

I have a bunch of JavaScript files in the src/ directory that I don't want to individually require. |- /src |- a.js |- b.js |- c.js |- more.js | - index.js index.js import a from 'a.js' import a from 'b.js' import ...

An example of using quotes within quotes is an HTML tag embedded within JavaScript code

Currently, I'm working on a JavaScript code where clicking assigns the function getImage the source of an image to be displayed later on the page. The issue I'm facing revolves around dealing with quotation marks. <img src="bill.jpg" class=" ...

Creating a pop-up window in Shiny that activates when switching tabs

Is there a way to create a popover/tooltip in a Shiny app that automatically appears when users switch to a specific tab containing a data table? I have tried using the shinybs package to create a popover that shows on click or hover, but I need it to appe ...

Is it advisable to avoid circular imports in typescript development?

After spending 4 long hours troubleshooting a TypeScript error, I finally found the root cause. Object literal may only specify known properties, and 'details' does not exist in type 'Readonly<{ [x: `details.${string}.value`]: { value: st ...

Is there a way to create Angular components sourced from an external library using JavaScript?

I'm currently developing an Angular project and leveraging an external component library called NGPrime. This library provides me with a variety of pre-built components, including <p-button> (which I am using in place of a standard <button> ...

In Laravel, a post request can pass a class with a property that is of a different class type

In my Laravel controller, I have the following function: public function save(Request $request, ClientOrderDTO $clientOrderDTO){ } The definition of the ClientOrderDTO used above is as follows: use App\DTO\ClientDTO; class ClientOrderD ...

The collapse feature in Bootstrap 4's navbar is not functioning properly, as it fails to stay open as intended

I've been working on setting up a Navbar using Bootstrap 4, and I'm facing an issue where the menu collapses rapidly after opening on mobile view. You can see this behavior in action at www.vitaminak.com.br or with just the code below: . The HTML ...

Implementing a feature to close the drawer component from the main page by clicking on the menu button in React-js

Just starting out with reactjs and I've got my main page set up like this: <div > <AppBar position="flex" style={{backgroundColor:'#1A437E'}}> <Toolbar> <IconButton edge="end" color= ...

Steps to invoke a function in a PHP file from an external JavaScript file

Can anyone assist me with calling the function below in my PHP file? function update_hidden_input(saved_tokens, hidden_input) { var token_values = $.map(saved_tokens, function (el) { //alert(el[settings.tokenValue]); return el[ ...