Angular 6 HttpClient返回类的实例

时间:2018-05-21 15:51:22

标签: angular typescript angular-http angular-httpclient

在引入angular的新HttpClient之前,可以使用instanceof关键字验证从http api调用返回的对象。他们不再能够使用HttpClient模块了。我正在尝试一些简单的方法,但类型检查每次都返回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
        })
}

```

会返回true。有没有人知道在http客户端幕后新建一个实例的简单方法?

1 个答案:

答案 0 :(得分:6)

TypeScript使用structural typing,即c对象不必是Cow 的实例,以符合Cow

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

应设计一个类来支持水合(可能通过构造函数参数)并明确实例化:

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静态方法)中完成。 / p>