首页 > 解决方案 > 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)

我该如何解决这个问题?

谢谢

标签: angular

解决方案


想提出几个问题:

  1. students您的 JSON 中不存在。
  2. student一个对象不是Student数组
  3. 附加的 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));
      }
    );
}

StackBlitz 上的示例解决方案 1


解决方案 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;
}

StackBliz 上的示例解决方案 2


推荐阅读