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();