Angular class 的 6 个 HttpClient return 实例

Angular 6 HttpClient return instance of class

在引入 angular 的新 HttpClient 之前,我们从 http api 调用 return 编辑的对象可以使用 instanceof 关键字进行验证。他们不再可以使用 HttpClient 模块。我正在尝试一些简单的方法,但类型每次都检查 return false。期望的行为:

```

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
        })
}

```

会 return 正确。有谁知道在 http 客户端的幕后新建实例的简单方法吗?

TypeScript 使用 structural typing,即 c 对象不必是 Cow class 的实例符合Cow类型.

TypeScript 类型仅在编译时存在,不会以任何方式影响 JS 输出(用于 Angular DI 的发射类型除外)。 as Cow 断言 res 符合 Cow 类型,而 instanceof Cow 期望 cCow class 的实例。由于 Cow 未实例化,因此 cow instanceof Cow 为假。

A class 应设计为支持水合作用(可能通过构造函数参数)并明确实例化:

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 实例(验证、嵌套对象构造),这可以在 class 构造函数或单独的辅助函数(例如 Cow静态方法)。