I'm facing some weird (to me) problem with objects and types in typescript/angular.
I have some class describing my objects received from remote API:
export class Point {
lat:number;
lng:number;
name:string;
public doSomething() {
console.log("doSomething called");
}
}
I'm using HttpClient to get objects from API:
constructor(private http:HttpClient) {}
getPointsAsync(callback: (points: Point[]) => {}) {
this.http.get<Point[]>(`${environment.apiUrl}/api/points`)
.subscribe(
(result: Point[]) => {
//do something with data
callback(result);
},
error => { //some error handling
}
);
}
My problem is that when I try to call method doSomething on one of my Point from array
var firstPoint = points[0];
firstPoint.doSomething()
I get some weird error on console:
ERROR TypeError: firstPoint.doSomething is not a function
I'm not using Typescript and Angular for very long so I'm assuming that it is something wrong with my code but I couldn't find answer to my issue. Could you give me some advice?
The problem is that you don' actually get instances of Point from the web service. You get a JSON object that has the class fields, but not the methods. You can use instantiate the class and use Object.assign to assign the values from the object literal to each Point instance
getPointsAsync(callback: (points: Partial<Point>[]) => {}) {
this.http.get<Point[]>(`${environment.apiUrl}/api/points`)
.subscribe(
(result: Partial<Point>[]) => {
let points = result.map(p=> Object.assign(new Point(), p));
callback(points);
},
error => { //some error handling
}
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With