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

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

问题描述

在引入 angular 的新 HttpClient 之前,我们从 http api 调用返回的对象可以使用 instanceof 关键字进行验证.他们不再可以使用 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 输入.

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 是假的.

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天全站免登陆