首页 > 解决方案 > Cannot get the Id through the API in the component(Angular, .net core)

问题描述

I'm developing a test project for learning Angular. My problem - the student's id from the service is equal to null. I have a controller - StudentController to work with data. Here is a snippet of code where I get data on students:

// GET: api/students
    [HttpGet]
    public IActionResult GetAll()
    {
        var students = _unitOfWork.Students.GetAll();
        return Ok(students);
    }

And here is my domain model(Student.cs) with UnitOfWork method - GetAll():

public class Student
{
    public int StudentId{get;set;}
    public string Name { get; set; }
    public DateTime bDate {get;set;} 
}

GetAll(Repository.cs):

public virtual IEnumerable<TEntity> GetAll()
    {
        return _entities.ToList();
    }

Next,I created a service for getting data from the API(student.service.ts):

  private readonly _StudentsUrl: string = "/api/students";
GetAll()
{
    return this.http.get(this._StudentsUrl)
    .map(res => res.json());
  }

So, in the client part student's id is undefined. (students.component.ts)

   export class StudentsComponent {
    students:Student[];
    constructor(private studentService: StudentService) { }

    ngOnInit() {
      this.studentService.GetAll()
      .subscribe(students => this.students = students);
    }
}
    export class Student {
        StudentId: number;
        Name: string;
        bDate:DateTimeFormat
      }

In student.component.html i get students data, name and bDate properly, but StudentId is not.

<tr *ngFor="let st of students">
    <td>{{ st.StudentId }}</td>
    <td>{{ st.name }}</td>
    <td>{{ st.bDate }}</td>
    <td>
      <a [routerLink]="['/students/', st.StudentId]">View</a>
    </td>
  </tr>

I tested my StudentController with Postman and everything is passed correctly.

What am i doing wrong?

标签: c#angulartypescript

解决方案


这很奇怪,但我通过在 studentId 上写而不是 StudentId 找到了解决方案。现在它完美地工作了。所以在html中我改变了:

<td>{{ st.StudentId }}</td>

至: <td>{{ st.studentId }}</td>

修改后的代码:

<tr *ngFor="let st of students">
        <td>{{ st.studentId }}</td>
        <td>{{ st.name }}</td>
        <td>{{ st.bDate }}</td>
        <td>
            <a [routerLink]="['/students/', st.studentId]">View</a>
        </td>
    </tr>

推荐阅读