javascript - 向所有 Angular 模型添加子类
问题描述
我正在将 AngularJS 用于 Web 应用程序,并且我正在尝试从 API 读取数据。因此,我根据 API 的结果集制作了几个模型。在众多模型中,让我们谈谈单个模型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 提供的pagination
数据在每个 API 响应中都很常见,但正如您所见,我的模型都没有使用它。pagination
在我的每个模型中存储和使用它的最佳方法是什么。我试图制作一个临时演示类,gallery.component.ts
如下所示,
export class TEMP {
records: TYPE[];
pagination: [];
}
但它很丑。有什么有效的解决办法吗?
解决方案
您的模型类并没有真正反映 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;
}
推荐阅读
- python - Python。将值更新到现有列excel
- c# - 如何在本地化和全球化中使用 If 语句?
- google-apps-script - 需要后处理写入 Google 表格的 Google 表单
- npm - 当我使用 npm install npm ERR 时出现此错误!Windows_NT 10.0.19041
- python - Jupyter Notebook 代码块不使用引号和特殊字符
- mysql - 使用 Node.JS 和 MySQL 插入数据库记录时出错
- linked-list - 二叉树遍历中序输出错误为什么?
- django - 为什么建议在 gitignore 中添加 sqlite 数据库?
- javascript - 计算表单输入中的数据
- javascript - 我可以做些什么来混合操作?使用香草 javascript