angular - Angular - 错误 TS2769:没有与此调用匹配的重载。重载 1 of 5, '(next: null | undefined, error: (error: any)
问题描述
在我的 Angular-12 中,我有以下代码:
界面
export interface IStudent {
id?: number;
first_name: string;
other_name: string;
last_name: string;
}
服务
getStudentById(id: number): Observable<IStudent[]> {
return this.http.get<IStudent[]>(this.api.baseURL + 'students/fetchbyid/' + id, this.httpOptions);
}
零件:
student!: IStudent;
id!: number;
ngOnInit(): void {
this.id = this.route.snapshot.params['id'];
this.loadStudentById();
}
loadStudentById() {
this.studentService.getStudentById(this.id).subscribe(
(data: IStudent) => {
console.log(data);
this.student = data.results.students;
},
error => {
this.store.dispatch(loadErrorMessagesSuccess(error));
}
);
}
console.log(this.id) 给出 1,这是正确的
console.log(data) 给出:
results
{
"student": {
"id": 1,
"first_name": "Lamptey",
"other_name": "Puel",
"last_name": "Akwetey",
}
}
我想根据 id 显示学生详细信息。
但是我在组件中遇到了这个错误:
错误 TS2769:没有重载匹配此调用。重载 1 of 5, '(next: null | undefined, error: (error: any)
它(数据:IStudent)
我该如何解决这个问题?
谢谢
解决方案
想提出几个问题:
students
您的 JSON 中不存在。student
是一个对象;不是Student
数组。- 附加的 JSON 无效,应该是:
{
"results": {
"student": {
"id": 1,
"first_name": "Lamptey",
"other_name": "Puel",
"last_name": "Akwetey"
}
}
}
解决方案 1
基于 JSON 的模型应该如下:
响应模型.ts
import { IStudent } from './student.model';
export class StudentResponse {
results: { student: IStudent };
}
学生服务.ts
import { StudentResponse } from '../models/response.model';
getStudentById(id: number): Observable<StudentResponse> {
return this.http.get<StudentResponse>(this.api.baseURL + 'students/fetchbyid/' + id, this.httpOptions);
}
.component.ts
import { StudentResponse } from '../models/response.model';
loadStudentById() {
this.studentService.getStudentById(this.id).subscribe(
(data: StudentResponse) => {
console.log(data);
this.student = data.results.student;
},
error => {
this.store.dispatch(loadErrorMessagesSuccess(error));
}
);
}
解决方案 2
StudentResponse
解决方案 1 中的可替换为以下模型。如果您有默认IResponse<T>
界面,建议使用此解决方案。
响应模型.ts
import { IStudent } from './student.model';
export class StudentKeyValuePair {
[student: string]: IStudent;
}
export class StudentResponse implements IResponse<StudentKeyValuePair> {
results: StudentKeyValuePair;
}
推荐阅读
- javascript - 使用 AJAX 查询填充表单字段
- html - 填充高度元素内的滚动元素
- jquery - jQuery class filtering and css transform delaying/blocking animation in section below it
- java - 如何在 SpringBoot 的 AuthenticationManagerBuilder 中设置范围子树
- r - 比较 5 k-mer 向量并找到唯一的向量
- java - 在多租户环境中发送电子邮件
- pandas - Pandas 获取数字分类数据的 dummies()
- android - 运行“ionic cordova build android”命令时如何解决无效或意外令牌问题?
- php - 在 Eloquent 关系中隐藏外国 id 列
- java - 如何将此嵌套的 json 字符串转换为 java 对象?