Reputation: 745
In my app, I have a model defined as Class with a constructor. Like this:
export class Movie {
title: string;
posterURL: string;
description: string;
public constructor(cfg: Partial<Movie>) {
Object.assign(this, cfg);
}
getEndDate(): Date {
return new Date();
}
};
I also have an HTTP request that uses this model
getMoviesData(): Observable<Movie[]> {
return this.http.get<Movie[]>(`http://localhost:3544/movies`)
}
As expected, it doesn't work
How can I solve this? Should I also create an interface or what?
Thanks for the help :)
Upvotes: 2
Views: 1667
Reputation: 223259
HttpClient
methods are generic, this.http.get<Movie[]>
asserts that the result conforms to Movie[]
interface and doesn't create Movie
instances.
In order for the result to become class instances, the class should be explicitly instantiated. Class constructor should preferably accept plain object which properties will be assigned to class instance, and Movie
already does this with cfg
parameter.
Since it's unlikely that Partial<Movie>
type precisely describes the interface, it's better to declare a separate interface:
interface IMovie {
title: string;
posterURL: string;
description: string;
}
class Movie implements IMovie { ... }
...
getMoviesData(): Observable<Movie[]> {
return this.http.get<IMovie[]>(...)
.map(plainMovies => plainMovies.map(plainMovie => new Movie(plainMovie)))
}
Upvotes: 6