javascript - 向所有 Angular 模型添加子类

标签 javascript angular api class model

我正在将 AngularJS 用于 Web 应用程序,并尝试从 API 读取数据。因此我根据API的结果集制作了一些模型。在众多 Model 中,我们来谈谈单个 Model TYPE

//This is the JSON API is returning
{ 
   "records":[ 
      { 
         "ID":"1",
         "TYPE":"mythological"
      }
   ],
   "pagination":{ 
      "count":"1",
      "page":1,
      "limit":10,
      "totalpages":1
   }
}

现在我为 TYPE 制作了以下模型

//type.ts
export class Type {
    "ID":string;
    "TYPE":string;  
}

从 API 获取数据后,我成功存储它并使用以下 TYPE 组件 ts 运行我的代码。

//gallery.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/services/data.service';
import { Type } from 'src/app/models/type';

@Component({
  selector: 'app-gallery',
  templateUrl: './gallery.component.html',
  styleUrls: ['./gallery.component.scss']
})
export class GalleryComponent implements OnInit {
  types: Type;
  constructor(private data: DataService) { }
  ngOnInit() {
  }
  clickfunction(){
    this.data.getData().subscribe(data=>{
        this.types=data.records;
        console.log(this.types);
    }); 
  } 
}

另外,我正在从此服务中获取数据

//data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  dataUrl:string = 'http://localhost/api-slim/public/index.php/api/info/type';

  constructor(private http: HttpClient) { }

  getData() {
    return this.http.get(this.dataUrl);
  }

}

尽管应用程序正在运行,但它显然给了我以下错误,我需要根除该错误。

Date: 2019-09-26T19:42:06.903Z - Hash: a1b41d5889df87ba0aa3
5 unchanged chunks

Time: 780ms
ℹ 「wdm」: Compiled successfully.

    ERROR in src/app/components/gallery/gallery.component.ts(23,21): error TS2339: Property 'records' does not exist on type 'Object'.

现在

API 提供的分页数据在每个 API 响应中都很常见,但正如您所看到的,我的模型都没有使用它。在我的每个模型中存储和使用分页的最佳方式是什么?我尝试在 gallery.component.ts 中制作一个临时演示类,如下所示,

export class TEMP {
  records: TYPE[];
  pagination: [];
}

但是很丑。有什么有效的解决办法吗?

最佳答案

您的模型类并未真正反射(reflect) API 响应。

模型就像一个自定义数据结构,您可以像这样使用数据类型:

export TEMP { //consider renaming this to something more meaningful
   records: Array<Type>;
   pagination: Pagination;
}

export class Type {
   ID: string;
   TYPE: string;  
}

export Pagination{
   count: string;
   page: number;
   limit: number;
   totalpages: number;
}

关于javascript - 向所有 Angular 模型添加子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58123400/

相关文章:

javascript - 我的 JS/jQuery 创建 div 有困难

javascript - 使用 JS/jQuery 获取位置固定的元素

javascript - 如何在 while 循环内异步发出后续 http 请求而不使用 Promise 和 async/await?

javascript - 使用 Google Translate API 进行翻译时排除 HTML 标签

javascript - 离李最近的图片

javascript - Polymer 2 铁选择器选择的元素在 dom 更改元素顺序后不会更新

javascript - Angular2 可以在 Chrome 中工作,但不能在 Firefox 中工作

angular - ionic 深层链接

angular - 从服务动态确定 loadChildren 模块类型

javascript - 现场示例 Spotify WEB 应用程序