问题描述
在引入angular的新HttpClient之前,可以使用instanceof
关键字验证从http api调用返回的对象.他们不再可以使用HttpClient模块.我正在尝试一些简单的方法,但是每次类型检查都会返回false.所需的行为:
Before angular's new HttpClient was introduced, our objects returned from the http api call could be validated with the instanceof
keyword. they no longer can with the HttpClient Module. I'm trying some simple methods but the type checks return false every time. 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
})
}
```
将返回true.有谁知道在http客户端幕后创建实例的简单方法吗?
would return true. does anyone know of a simple way to new up an instance behind the scenes of the http client?
推荐答案
TypeScript使用结构化类型,即c
对象不必是Cow
class 的实例即可符合Cow
type .
TypeScript uses structural typing, i.e. c
object doesn't have to be an instance of Cow
class to conform to Cow
type.
TypeScript类型仅在编译时存在,并且不会以任何方式影响JS输出(用于Angular DI的发射类型除外). as Cow
断言res
符合Cow
类型,而instanceof Cow
期望c
是Cow
类的实例.由于未实例化Cow
,因此cow instanceof Cow
为false.
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). as Cow
asserts that res
conforms to Cow
type, while instanceof Cow
expects that c
is an instance of Cow
class. Since Cow
wasn't instantiated, cow instanceof Cow
is false.
应该将一个类设计为支持水合(可能通过构造函数参数)并显式实例化:
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);
})
如果需要某种逻辑从普通对象构造Cow
实例(验证,嵌套对象构造),则可以在类构造函数或单独的辅助函数(例如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 (e.g. Cow
static method).
这篇关于Angular 6 HttpClient返回类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!