Angular 6 HttpClient返回类的实例 [英] Angular 6 HttpClient return instance of class

查看:275
本文介绍了Angular 6 HttpClient返回类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在引入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期望cCow类的实例.由于未实例化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返回类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆