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

查看:58
本文介绍了将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<MyClass[]>('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天全站免登陆