我是Angular的新手。请原谅我微不足道的事情。
我正在尝试进行API调用。为此,我创建了一个名为base.service.ts的基本服务类(下面需要代码)-
503.mp4
我还创建了一个名为visitor.service.ts的新服务类,在该类中,我从下面调用基本服务的get方法-
public get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
return this.httpClient.get(BASE_URL + path, { params }).pipe(catchError(this.formatErrors));
}
从名为dashboard.component.ts的组件类中,加载此访问者列表-
export class VisitorService {
constructor(private baseService: BaseService) { }
getVisitors(): Observable<Visitor[]> {
return this.baseService.get(String.Format(Globals.endpoints.visitors));
}
}
我的第一个问题是-运行此代码时,控制台上没有任何记录。为什么?
此外,我的回复将采用以下格式-
export class DashboardComponent implements OnInit {
constructor(private visitorService: VisitorService) { }
ngOnInit() {
this.loadTodaysVisitors();
}
private loadTodaysVisitors() {
this.visitorService.getVisitors().subscribe(
data => {
console.log(data)
}
);
}
}
我为此命名为visitor.model.ts创建了访客模型-
[
{
"visitor": {
"attendeeFirstName": "ABC",
"attendeeSurname": "XYZ",
},
"visitorcheckin": [
{
"field": value,
"field1": value1,
},{
"field": value,
"field1": value1,
}
],
"visitorcheckout": [
{
"field": value,
"field1": value1,
},{
"field": value,
"field1": value1,
}
]
},
{
"visitor": {
"attendeeFirstName": "DEF",
"attendeeSurname": "PQR",
},
"visitorcheckin": [
{
"field": value,
"field1": value1,
},{
"field": value,
"field1": value1,
}
],
"visitorcheckout": [
{
"field": value,
"field1": value1,
},{
"field": value,
"field1": value1,
}
]
},
]
desrializable.interface.ts文件-
import { Deserializable } from '../interfaces/deserializable.interface';
export class Visitor implements Deserializable {
attendeeFirstName: string;
attendeeSurname: string;
deserialize(input: any): this {
Object.assign(this, input);
return this;
}
}
这是为上述类型的响应结构创建模型的正确方法吗?另外,如何将响应映射到模型对象以及如何在dashboard.component.ts中使用它们?
谢谢!
答案 0 :(得分:1)
您的JSON无效,我已经更正了,应如下所示,
[ { “访客”:{ “ attendeeFirstName”:“ ABC”, “ attendeeSurname”:“ XYZ” }, “ visitorcheckin”:[ { “ field”:“ value”, “ field1”:“值” }, { “ field”:“ value”, “ field1”:“值” } ], “ visitorcheckout”:[ { “ field”:“ value”, “ field1”:“值” }, { “ field”:“ value”, “ field1”:“值” } ] }, { “访客”:{ “ attendeeFirstName”:“ DEF”, “ attendeeSurname”:“ PQR” }, “ visitorcheckin”:[ { “ field”:“ value”, “ field1”:“值” }, { “ field”:“ value”, “ field1”:“值” } ], “ visitorcheckout”:[ { “ field”:“ value”, “ field1”:“值” }, { “ field”:“ value”, “ field1”:“值” } ] } ]
您可以使用JSON2TS为模型创建接口,结果接口如下所示,
declare module namespace {
export interface Visitor {
attendeeFirstName: string;
attendeeSurname: string;
}
export interface Visitorcheckin {
field: string;
field1: string;
}
export interface Visitorcheckout {
field: string;
field1: string;
}
export interface RootObject {
visitor: Visitor;
visitorcheckin: Visitorcheckin[];
visitorcheckout: Visitorcheckout[];
}
}