gpt4 book ai didi

java - 如何使用 header 和 body 调用 java api 来列出 Angular 中的对象?

转载 作者:行者123 更新时间:2023-12-01 18:10:00 25 4
gpt4 key购买 nike

我想列出调用 java api 的学生详细信息,其响应如下。我想要来自具有多个值的数据的值。下面是我在 component.ts 类中调用的方法。

ngOnInit() {
this.loading = true
this.httpService.get('/student').subscribe(
result => {
console.log('received results');
this.loading = false;
this.scouts = result;
},
error => {
console.log('failed');
this.loading = false;
}

``
This is the api response.
``
{
data: [
{
id: 101,
name: "John doe",
status: "enrolled",
}
],
errors: [ ],
warnings: [ ],
meta: { }
}
```

I tried to using this as html code but this won't work and in the component part i have called the httpservice with get request in ngOnInit part.
``
<tr *ngFor="let student of students">
<td>{{student.id}}</td>
<td>{{student.name}}</td>
<td>{{student.status}}</td>
```

Please can you guide me how can i get the student details from data part and list it in front end. Thank you.

最佳答案

来自最佳实践:

在服务级别使用 url(因为它是仅在服务内部使用的常量)

定义一个 StudentResponce 模型,以便您可以获取 json 响应。

定义 Student 模型,该模型将成为 StudentReponse 的属性

那么你的组件就变成了

 ngOnInit() {
this.loading = true;
this.httpService.getStudents().subscribe(
result => {
console.log('received results');
this.loading = false;
this.scouts = result.data;
/*or this.scouts = [...result.data] */
//warning = result.warning
//meta = result.meta
//errors = [...result.errors]
},
error => {
console.log('failed');
this.message = error.message;
this.loading = false;
});
}

和服务

 const url = "http://replace_with_service_url";
@Injectable()
export class MyHttpService {

constructor(private client: HttpClient) {
}
getStudents(): Observable<StudentResponse>{
return this.client.get<StudentResponse>(url);
}
}
export class StudentResponse{
data: Student[];
warning: any;
errors: any[];
meta: any;
}
export class Student{
id: number;
name= "";
status: string /*or enum "enrolled"*/;
}

您可以将您的服务网址替换为 this code测试

关于java - 如何使用 header 和 body 调用 java api 来列出 Angular 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60483926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com