Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将httpClient应答转换为模型对象[6]_Javascript_Angular_Typescript_Angular6 - Fatal编程技术网

Javascript 将httpClient应答转换为模型对象[6]

Javascript 将httpClient应答转换为模型对象[6],javascript,angular,typescript,angular6,Javascript,Angular,Typescript,Angular6,我有一个关于Angular 5 httpClient的问题 这是一个带有方法foo()的模型类,我希望从服务器接收该方法 export class MyClass implements Deserializable{ id: number; title: string; deserialize(input: any) { Object.assign(this, input); return this; } foo(): string { // re

我有一个关于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')
  }
}
从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpClient};
从“rxjs”导入{Observable};
从“/MyClass”导入{MyClass};
@注射的({
providedIn:'根',
})
导出类MyClassService{
构造函数(专用http:HttpClient){
}
getMyStuff():可观察{
//这就是我希望将json转换为MyClass实例的地方
返回此.http.get('api/stuff')
}
}
我的问题 当我向服务请求
MyClass
的实例时,我得到了数据,但我无法在模板中运行
{{item.foo()}
。另外,当我
console.log()
服务中接收到的项目的
类型时,我看不到
MyClass
对象的实例

我做错了什么?我认为编写
this.http.get('api/stuff')
可以完成转换


有什么提示吗?提前谢谢你

执行此操作时,TypeScript只执行“类型断言”。这意味着您告诉TypeScript您的对象是
MyClass
类型,但在运行时该对象实际上不是
MyClass
的实例。为了调用模型对象中定义的函数,必须在模型类中定义构造函数,如下所示:

constructor(obj?: any) {
    Object.assign(this, obj);
}
然后在您的服务中添加如下映射:

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

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

import { HttpClient } from '@angular/common/http';

...
this.httpClient.get<MyResponse>('http://......').toPromise()
      .then((myResponse) => {
        console.log('myResponse.myField: ' + JSON.stringify(tokenResponse));
      })
      .catch((error) => {
        console.log('Promise rejected with ' + JSON.stringify(error));
      });

...
interface MyResponse {
  myField: string;
  myOtherField: string;
}
从'@angular/common/http'导入{HttpClient};
...
this.httpClient.get('http://......)。toPromise()
。然后((myResponse)=>{
log('myResponse.myField:'+JSON.stringify(tokenResponse));
})
.catch((错误)=>{
log('承诺被拒绝,带有'+JSON.stringify(错误));
});
...
接口MyResponse{
myField:字符串;
myOtherField:字符串;
}

阅读此内容,了解如何在模型中使用API数据的反序列化功能。类似问题与此处的类似问题多亏了您,我重新阅读了我最后没有做的事情。我现在在服务中做的是:`return stuffObjects.map(stuff=>new MyClass().deserialize(stuff));不客气,我个人喜欢构造函数的方式,
反序列化
接口是另一个合适的选项这只在
MyClass
没有复杂成员(例如类型
Date
或其他类的成员)时才起作用@Jota.Toledo是的,这可以通过为这些属性定义setter来解决。Hank非常有用,请在您的答案中添加一些解释,以便其他人可以从中学习。请再次阅读问题,它是关于在从后端水合的业务类上调用函数,接口如何解决此问题?@GuerricP这个问题是关于将服务器响应反序列化到模型中,这正是我的代码所做的。