Converting httpClient answer to model objects [Angular 6]

匆匆过客 提交于 2019-11-30 08:56:50

When doing that, TypeScript only does "type assertion". It means that you're telling TypeScript that your object is of type MyClass, but the object isn't actually an instance of MyClass at runtime. In order to call functions defined in your model object, you have to define constructors in your model classes like that :

constructor(obj?: any) {
    Object.assign(this, obj);
}

Then in your services add a mapping like this :

http.get<MyClass>('/my-class').pipe(
      map(res => new MyClass(res))

Note: the code above is RxJS 6 style, i don't know which version you are using

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