无法将 HttpClient 响应转换为对象数组

Cannot convert HttpClient response to object array

如何将 HttpClient 响应投射或转换为 Angular 中的自定义 class 对象数组?

我有这样的提供商:

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

错误:

ERROR TypeError: _this.clients[0].getName is not a function

我什至试过了

(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 的类型提示和转译器的简要类型控制)。

没有 Client class 的实例可以调用方法。

如果您希望它成为 class 的实例,您必须首先像这样映射整个响应:

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

类型提示与转换不同。您不能执行 as Client 并期望对象变成 Client class 并在其中包含所有方法。你需要映射它:

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());
});

问题

您的方法存在问题,您正试图将响应分配给 Client[] 数组。然而,它只是将 response data 赋值给 client 变量。

修复

如果您想将响应转换为各个模型 class,那么您需要从模型 class 本身处理它。

例如:

在模型中创建构造函数class

导出class客户端{

constructor(obj?: any) {
   Object.assign(this, obj);
}

id: number;
name: string;

getName() {
return this.name;
}

}

getClient() {
     this.http.get(this.url)
  .subscribe(
      (response) => {
        let clients = this.response.map(item=>new Client(item)); //Create new instance of client and set the properties.
       });

Note : Check the type of response. The above implementation when the response contains the multiple client.

您可以直接投出您的回复,然后这样做

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

       });
  }