将 httpClient 答案转换为模型对象 [Angular 6] [英] Converting httpClient answer to model objects [Angular 6]

查看:29
本文介绍了将 httpClient 答案转换为模型对象 [Angular 6]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 Angular 5 httpClient 的问题.

I have a question about the Angular 5 httpClient.

这是一个模型类,我想从服务器接收一个方法 foo()

export class MyClass implements Deserializable{
  id: number;
  title: string;

  deserialize(input: any) {
    Object.assign(this, input);
    return this;
  }

  foo(): string {
    // return "some string conversion" with this.title
  }
}

这是我的服务请求:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { MyClass } from './MyClass';

@Injectable({
  providedIn: 'root',
})
export class MyClassService {

  constructor(private http: HttpClient) {
  }

  getMyStuff(): Observable<MyClass[]> {
    // this is where I hope to convert the json to instances of MyClass
    return this.http.get<MyClass[]>('api/stuff')
  }
}

我的问题

当我向服务请求 MyClass 的实例时,我得到了数据,但我无法在模板中运行 {{ item.foo() }}.此外,当我 console.log() 在服务中接收到的项目的 typeof 时,我看不到MyClass 的对象.

My Problem

When I ask the service for instances of MyClass I get the data, but I cannot run {{ item.foo() }} in the template. Also, when I console.log() the typeof of an item where it is received in the service, I do no see instances of an object of MyClass.

我做错了什么?我认为编写 this.http.get('api/stuff') 会进行转换.

What am I doing wrong? I thought that writing this.http.get<MyClass[]>('api/stuff') would do the conversion.

有什么提示吗?提前致谢!

Any hints? Thank you in advance!

推荐答案

当这样做时,TypeScript 只做类型断言".这意味着您告诉 TypeScript 您的对象属于 MyClass 类型,但该对象实际上并不是运行时 MyClass 的实例.为了调用模型对象中定义的函数,您必须在模型类中定义构造函数,如下所示:

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

注意:上面的代码是RxJS 6风格,不知道你用的是哪个版本

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

这篇关于将 httpClient 答案转换为模型对象 [Angular 6]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆