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

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

A novel way to enhance a class: a decorator that incorporates the “identify” class method, enabling the retrieval

I have been given the task to implement a class decorator that adds an "identify" class method. This method should return the class name along with the information passed in the decorator. Let me provide you with an example: typescript @identity(' ...

Is it possible to deactivate the onclick event following a successful ajax request?

I am looking to disable the onclick event after a successful ajax request. <div class="report_button" id="report_button" title="Reportthis" style="width:65px;height:15px;" onclick="reported_text(user_id,lead_id);">Report</div> This is the div ...

You cannot invoke this expression while destructuring an array of React hooks in TypeScript

Within my React TypeScript component, I have several fields that check a specific condition. If the condition is not met, the corresponding field error is set to true in order to be reflected in the component's DOM and prevent submission. However, whe ...

Utilizing an SSL certification (pem file) within JavaScript

Currently in the process of developing a program to extract data from the FAA's AIDAP database. I received a security certificate in the form of a .p12 file, which I have successfully converted into a .pem file. However, I am encountering difficulties ...

What could be causing the recurring appearance of the success alert message in an AJAX call to a PHP script in this particular situation?

Below you will find two code blocks, each designed to handle an AJAX call to a PHP file upon clicking on a specific hyperlink: <script language="javascript" type="text/javascript"> $(".fixed").click(function(e) { var action_url1 = $(th ...

Troubleshooting fastify library errors related to ajv validation

Every time I try to build my TypeScript code, I encounter these errors: The following errors are showing up in my TypeScript code: 1. node_modules/@fastify/ajv-compiler/types/index.d.ts(1,10): error TS2305: Module 'ajv' has no exported member ...

Using Angular 2 to assign a function to the ngClass directive within the template

I've been searching for a solution to this issue, but so far nothing has worked for me. When I try to pass a function to the ngStyle directive, I encounter the following error: The expression 'getClass()' in ProductView has changed after i ...

Node.js offers a simple and effective way to redirect users to another page after they have

I am experiencing an issue when trying to redirect the client to the confirm page after a successful login process. I keep encountering some errors. view screenshot router.post('/sign_in', urlend, function(req, res) { var email = req.body.user ...

Do you think this is a clever way to circumvent using ENUM for a parameter?

As I continue to explore different coding styles in Typescript and Angular, I recently encountered a method without any comments attached to it. It seems like this method is enforcing that the value passed in must be one of the defined options, but strang ...

Retrieve the initial token from a union, referred to as an "or list," in Typescript

Is there a way to define a generic type F with the following behavior: type X = F<'a'|'b'|'c'> should result in X being 'a'. And if type X = F<'alpha'|'beta'|'gamma'|'del ...

Tips for preventing the playback of the sound while recording

When creating a basic JavaScript application that involves opening a stream from the user and analyzing frequencies, I found that while Google Chrome and Opera work well by providing feedback in the headphones, Firefox often remains silent. Additionally, F ...

Incorporate new content into JavaScript using the input element

I have a unique question - can text be added to JavaScript using the input tag? For example, <input type="text" id="example" /> And let's assume the JavaScript function is: function display_text() { alert("The text entered in #example wi ...

JQuery may be successfully loaded, but it is not functioning as intended

Just started dabbling in JQuery (I'm a newbie) but I'm having trouble getting it to work! Initially, it worked a couple of times but then suddenly stopped working (pretty strange). I made some changes and now it doesn't work at all. JQuery a ...

Utilizing PHP to create an interactive website

As a novice PHP developer, I took to Google in search of tutorials on creating dynamic PHP websites. What I found was that many tutorials used the $_GET variable to manipulate URLs and make them appear like this: example.com/?page=home example.com/?page= ...

Encountering a problem with AngularJS - receiving the [ng:areq] error, for more information visit http://errors.angularjs.org/1.3.2/ng/areq

While working on my CRUD angularApp, I encountered a strange error in Chrome dev tools. Here is the complete error message: error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=DbController&p1=not%20a%20function%2C%20got%20string at angular.j ...

Executing Basic Authentication in Javascript through window.open()

After a user logs into my app, they have the option to download a CSV file from the server by clicking on a button. The URL for the download is secured with basic authentication. When attempting to open the URL using the code below: window.open('http ...

Starting over fresh after clearing the interval

Visit the test site Is there a way to reset the animation back to the beginning once it reaches the last image? I've attempted the code below, but it doesn't seem to bring it back to the first image. $(document).ready(function () { window. ...

How to retrieve text values across various browsers using Vue.js

Whenever I type something in a text box, it displays the text value based on its ID. This code works perfectly when running it on my laptop at http://localhost:8080/. If I open the same website on my phone at http://xxx.xxx.x.xxx:8080/, it shows the same ...