Angular 无法将HttpClient响应转换为对象数组
如何将HttpClient响应转换为Angular中的自定义类对象数组 我有一个类似于:Angular 无法将HttpClient响应转换为对象数组,angular,ionic-framework,angular-httpclient,Angular,Ionic Framework,Angular Httpclient,如何将HttpClient响应转换为Angular中的自定义类对象数组 我有一个类似于: import { Client } from '../../models/client.model'; @Injectable() export class ClientProvider { clients: Client[] = []; url = "link/to/api/clients" //Should return an array of clients constructor(
import { Client } from '../../models/client.model';
@Injectable()
export class ClientProvider {
clients: Client[] = [];
url = "link/to/api/clients" //Should return an array of clients
constructor(public http: HttpClient){ }
getClient() {
this.http.get(this.url)
.subscribe(
(response) => {
this.clients = response as Client[];
console.log(this.clients[0]) // this works and shows the client info
console.log(this.clients[0].getName()); //this gives error (1)
});
}
错误:
错误类型错误:\此.clients[0]。getName不是函数
我甚至试过
(response: Client[]) => {
this.clients = response ...}}
但它给了我同样的错误
我的模型定义如下:
export class Client{
id: number;
name: string;
getName() {
return this.name;
}
}
尝试此console.log(this.clients[0].name)代码>
不需要在此处使用函数的名称。这不起作用。当您得到JSON响应时,框架为您所做的就是将JSON解析为普通对象。每个类型声明或转换都是无意义的,并且只在编译时有效(作为IDE的类型提示和transpiler的简短类型控制)
那里没有可调用方法的客户端
类的实例。
如果希望它是类的实例,则必须首先映射整个响应,如下所示:
getClient() {
this.http.get(this.url)
.pipe(
map(plainJson=> create new Client here from json)// HER Eyou must create CLIENT yourself from plain javascript object
)
.subscribe(
(response) => {
this.clients = response as Client[];
console.log(this.clients[0]) // this works and shows the client info
console.log(this.clients[0].getName()); //this gives error (1)
});
类型暗示与铸造不同。您不能将作为客户机
而期望对象成为客户机
类,并在其中包含所有方法。您需要映射它:
this.http.get(this.url).pipe(
map((clients) => clients.map((client) => ({ ...new Client(), ...client}))
)
.subscribe(
(clients) => {
console.log(clients[0]) // this works and shows the client info
console.log(clients[0].getName());
});
问题
您的方法的问题是,您正在尝试将响应分配给客户端[]数组。然而,它只是将响应
数据
分配给客户端
变量
修理
如果要将响应转换为相应的模型类,则需要从模型类本身处理它
前任:
在模型类中创建构造函数
导出类客户端{
constructor(obj?: any) {
Object.assign(this, obj);
}
id: number;
name: string;
getName() {
return this.name;
}
}
注意:检查响应的类型。当响应包含多个客户机时,将执行上述实现
你可以直接做出回应,然后这样做
getClient() {
this.http.get<Array<Client>>(this.url)
.subscribe(
(response) => {
/*here you can directly iterate response and get Client objects*/
for(let client in response){
console.log(client.name);
}
});
}
getClient(){
this.http.get(this.url)
.订阅(
(回应)=>{
/*在这里,您可以直接迭代响应并获取客户机对象*/
for(让客户端响应){
console.log(client.name);
}
});
}
请在屏幕上添加控制台中的日志。是的,我知道,但这只是一个示例,因为我以后还需要一些其他功能;我想我会把他们的反应映射为上面的答案
getClient() {
this.http.get<Array<Client>>(this.url)
.subscribe(
(response) => {
/*here you can directly iterate response and get Client objects*/
for(let client in response){
console.log(client.name);
}
});
}