我正在将 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/