[英]Angular 6 HttpClient return instance of class
Before angular's new HttpClient was introduced, our objects returned from the http api call could be validated with the instanceof
keyword.在引入 angular 的新 HttpClient 之前,我们从 http api 调用返回的对象可以使用instanceof
关键字进行验证。 they no longer can with the HttpClient Module.他们不再可以使用 HttpClient 模块。 I'm trying some simple methods but the type checks return false every time.我正在尝试一些简单的方法,但类型检查每次都返回 false。 the desired behavior of:期望的行为:
``` ``
getCow() {
return this.http.get<Cow>(ApiRoute.GET_COW, options)
.map(res => res as Cow)
.toPromise()
.then((c: Cow) => {
console.log(c instanceof Cow); //this is false
})
}
``` ``
would return true.会返回true。 does anyone know of a simple way to new up an instance behind the scenes of the http client?有谁知道在 http 客户端的幕后新建一个实例的简单方法?
TypeScript uses structural typing , ie c
object doesn't have to be an instance of Cow
class to conform to Cow
type . TypeScript 使用结构类型,即c
对象不必是Cow
类的实例以符合Cow
类型。
TypeScript types exist only at compilation time and don't affect JS output in any way (with the exception of emitted types which are used for Angular DI). TypeScript 类型仅在编译时存在,不会以任何方式影响 JS 输出(用于 Angular DI 的发射类型除外)。 as Cow
asserts that res
conforms to Cow
type, while instanceof Cow
expects that c
is an instance of Cow
class. as Cow
断言res
符合Cow
类型,而instanceof Cow
期望c
是Cow
类的实例。 Since Cow
wasn't instantiated, cow instanceof Cow
is false.因为Cow
没有被实例化,所以cow instanceof Cow
是假的。
A class should be designed to support hydration (possibly via constructor parameters) and be instantiated explicitly:一个类应该被设计为支持水化(可能通过构造函数参数)并被显式实例化:
class Cow {
sound: string;
}
return this.http.get<Cow>(ApiRoute.GET_COW, options)
.map(res => Object.assign(new Cow(), res as Cow))
.toPromise()
.then((c: Cow) => {
console.log(c instanceof Cow);
})
If some logic is needed to construct Cow
instance from plain object (validation, nested object construction), this can be done in class constructor or separate helper function (eg Cow
static method).如果需要一些逻辑来从普通对象构造Cow
实例(验证、嵌套对象构造),这可以在类构造函数或单独的辅助函数(例如Cow
静态方法)中完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.