Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object instances and properly initializing them.

A recent puzzling issue I encountered involves sending a HTTP GET request and receiving its response as a Javascript Object. To manipulate this response, I'm attempting to map it to a custom typescript class named HttpResponse. However, upon receiving the response, creating an instance of HttpResponse results in an empty object, which has left me puzzled and seeking answers.

To simplify the problem, I put together a quick fiddle to illustrate the issue. You can view it here.

The output shows that the object data is present, but when instantiating the HttpResponse class, it remains empty without any data. I'm unsure why this is happening and would greatly appreciate any assistance or insights on this matter!

  class HttpResponse {
    constructor(status: number = 0,
    data: string =  '',
    headers: Object =  '',
    error: string =  ''){}
}


  class Page {

      response: HttpResponse;

      retrieveData(): void {
        document.body.innerHTML += 'inside retrieveData()<br>';
        let data = {
          status: 200, data: "this is some fake data",
          headers: { foo: 'foo', bar: 'bar', baz: 'baz' }
        }
        document.body.innerHTML +='Data: ' + JSON.stringify(data) + '<br>';
        this.response = new HttpResponse(data.status, data.data, data.headers);
        document.body.innerHTML += JSON.stringify(this.response);

      }

  }

 new Page().retrieveData();

Answer №1

When initializing your HttpResponse class, make sure to assign the passed arguments to the properties of the class within the constructor. You can achieve this by using the public keyword for the parameters.

class HttpResponse {
  constructor(public status: number = 0,
  public data: string =  '',
  public headers: Object =  '',
  public error: string =  ''){ }
}

Take a look at the updated Fiddle.

Alternatively, you have the option to define the properties in your class and set them in the constructor using assignments like this.data = data;.

Answer №2

One reason for this is that your HttpResponse does not actually contain any properties. Instead, it only has constructor parameters and nothing else. To automatically turn these constructor parameters into properties, you can utilize parameter properties:

class HttpResponse {
    constructor(
    public status: number = 0,
    public data: string =  '',
    public headers: Object =  '',
    public error: string =  ''){}
}

Answer №3

In order to define constructor parameters, it is necessary to use access modifiers such as private, public, or protected.

class HttpResponse {
    constructor(
     private statusCode: number = 200,
     private responseData: string = '',
     private responseHeaders: Object = {},
     private errorMessage: string = ''){}
}

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

Identifying the presence of a mouse inside an element using jQuery

I am working on a website that utilizes jQuery. The structure of my page is as follows: <div id="page"> <!-- Content goes here --> <div id="content"> <div class="row"> <div class="col"><!-- content goes here ...

Retrieving the value of the button with $(this).val() is the only function that newusername performs

My issue arises when trying to send my data to a PHP file; it only sends the value of the <button> or <input type="button">. If I remove the variable definitions, it will only send the data as a string if they are formatted like this: newuser ...

modify the tr element within a jQuery context

I am attempting to convert a "yes" to a select dropdown that allows users to choose between yes and no. The HTML structure is as follows: <tr> <td>text</td> <td>no (needs to be changed via JS)</td> <td><a href="#"&g ...

Using Javascript's Speech Recognition to activate a button

I am new to using JavaScript Speech Recognition and decided to work with the Annyang library. My goal is to automatically trigger the "show date" button when the user says 'hello', without actually clicking the button. However, I've been fac ...

Solving Issues with URL Parameters and AJAX

My JSP page has a JavaScript function called loadData() that is triggered when the page loads. This function makes an AJAX request to a servlet in order to retrieve data and return the necessary HTML content to display on the page. I am trying to call thi ...

Steps for importing a React component as an embedded SVG image

I have developed a SVG component in React by converting an SVG file to a React component using the svg-to-react cli tool. In order to load and display additional svg files within this component, I am utilizing the SVG image tag as demonstrated below. This ...

Switch up the animation based on the state in AngularJS

In my AngularJS application, I have implemented CSS animations for transitioning between states. The animations involve sliding content from left to right with specific timings and transforms. .content.ng-enter, .content.ng-leave { -webkit-animation-t ...

NextJS is throwing an error stating that the element type is invalid. It was expecting either a string for built-in components or a class/function for composite components, but instead received an object

I encountered the following issue: Error - Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but received an object. Here's the code from my \components\LayoutWrapper.js: i ...

Please enter data into the input fields provided in the text

Below is the code where Google transliteration is used for typing in Indian language in a text field. There are two routes with different page IDs. Initially, the transliteration works fine on the default page. However, when changing routes, an error occur ...

An Unexpected Typescript Error Occurred While Creating an RxCollection With RxDB

I'm new to RxDB and I've come across a strange Typescript error in my Electron project. Here are the relevant parts of my code: import RxDB, { RxCollection, RxDatabase } from "rxdb"; RxDB.plugin(require("pouchdb-adapter-idb") ...

Troubleshooting Typescript Compilation Error in React - Cannot assign type 'Element' to type 'FunctionComponent<{}>'

The code snippet originally utilized - import { Create } from '@material-ui/icons'; <DroppableFolder count={draftsCount} sidebarOpen={open} folderId={FolderType.Drafts} Icon={Create} name="Dr ...

Encountered an Angular 2 error: NullInjectorError - Http provider not found

I've encountered an issue while trying to access a JSON GitHub service, receiving the error message NullInjectorError: No provider for Http! Although I've attempted to add providers throughout the code, my efforts have been unsuccessful. I' ...

Updating the parent page host within a cross-domain iframe: issues encountered in Firefox and Chrome browsers

I am encountering an issue with my iframe app where I am receiving an alert indicating "-error" in Chrome related to top.location.href. jQuery.ajax({ type : 'get', url : 'check_if_fb_data_set.php', success ...

What is the procedure for obtaining FlowNode in the typescript ast api?

Trying to access and resolve foo and bar from the nodes variable. Upon examination in ts-ast-viewer, it is evident that TypeScript recognizes foo and bar within the nodes node under the FlowNode section (node -> initializer -> elements -> escaped ...

Unable to update a property with a new value in Vue.js when using the keyup.enter event on an input element bound to that property

I am facing an issue with inputs that have the @keyup.enter event assigned to a method that is supposed to reset the value of variables bound to these inputs to null. Here is an example of my code: methods:{ clear: function () { this.somethin ...

Tips for switching the status of each item as I navigate the page with the tab key

I am facing an issue with my list of items that have hidden content appearing on hover. I want to achieve the same functionality while tabbing through my page, but currently, all hidden content appears at once. Check out a live example of my code here jQ ...

"Encountered an error while trying to define a Boolean variable due

I am in the process of creating a TF2 trading bot with price checking capabilities. I encounter an issue while trying to define a boolean variable to determine if the item is priced in keys or not. My attempt at replacing isKeys with data[baseName].prices ...

Making If Statements Easier

Currently, I'm tackling an assignment that involves utilizing if statements and switch statements. Here is a snippet of code that I am working on: if (validateField(document.forms[0].name) == false) { isValid = false; } if (validateField(docume ...

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...

Customize the initial color of the text field in Material UI

I am currently working with the mui TextField component and facing an issue. I am able to change the color when it is focused using the theme, but I cannot find a way to adjust its color (label and border) in its initial state when it's not focused. I ...