问题描述
在我的应用程序中,我有一个带有构造函数的定义为Class的模型.像这样:
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();
}
};
我还有一个使用此模型的HTTP请求
I also have an HTTP request that uses this model
getMoviesData(): Observable<Movie[]> {
return this.http.get<Movie[]>(`http://localhost:3544/movies`)
}
按预期,它不起作用
我该如何解决?我还应该创建一个界面还是什么?
How can I solve this? Should I also create an interface or what?
感谢您的帮助:)
推荐答案
HttpClient
方法是通用的,this.http.get<Movie[]>
断言结果符合Movie[]
接口,并且不会创建Movie
实例.
HttpClient
methods are generic, this.http.get<Movie[]>
asserts that the result conforms to Movie[]
interface and doesn't create Movie
instances.
为了使结果成为类实例,应显式实例化该类.类构造函数最好应接受将对象属性分配给类实例的普通对象,并且Movie
已经使用cfg
参数进行了此操作.
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.
由于Partial<Movie>
类型不太可能精确描述该接口,因此最好声明一个单独的接口:
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)))
}
这篇关于Angular 4:带有构造函数作为http Observable模型的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!