Angular 6 HttpClient return instance of class

断了今生、忘了曾经 提交于 2019-12-01 04:09:09

TypeScript uses structural typing, i.e. c object doesn't have to be an instance of Cow class to conform to Cow type.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!