typescript 将 httpClient 答案转换为模型对象 [Angular 6]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50551649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting httpClient answer to model objects [Angular 6]
提问by Colja
I have a question about the Angular 5 httpClient.
我有一个关于 Angular 5 httpClient 的问题。
This is a model class with a method foo() I'd like to receive from the server
这是一个模型类,我想从服务器接收一个方法 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
}
}
This is my service requesting it:
这是我的服务请求:
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')
}
}
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 seeinstances of an object of MyClass
.
当我向服务请求MyClass
获取数据的实例时,我无法{{ item.foo() }}
在模板中运行。此外,当我console.log()
将typeof
它在服务接收的邮件,我根本没有看到的对象的实例MyClass
。
What am I doing wrong?I thought that writing this.http.get<MyClass[]>('api/stuff')
would do the conversion.
我究竟做错了什么?我认为写作this.http.get<MyClass[]>('api/stuff')
会进行转换。
Any hints? Thank you in advance!
任何提示?先感谢您!
回答by Guerric P
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 :
这样做时,TypeScript 只执行“类型断言”。这意味着您告诉 TypeScript 您的对象是 type MyClass
,但该对象实际上并不是MyClass
运行时的实例。为了调用模型对象中定义的函数,您必须在模型类中定义构造函数,如下所示:
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
注意:上面的代码是RxJS 6风格,不知道你用的是哪个版本
回答by interrupt
It works for me like this
它像这样对我有用
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;
}