When initializing my component, it fetches student information from an API. Here is the ngOnInit code for component-version1:
ngOnInit(): void {
if(!this.student) {
this.studentsService.getStudentDetail(this.id).subscribe(
(response: Student) => {
this.student = response;
},
error => console.log(error)
)
}
}
Below is the method in student-service-version1:
getStudentDetail(id: number): Observable<Student> {
return this.httpClient.get<Student>(`${this.studentsUrl}${id}/`, this.baseService.httpOptions);
}
While everything works as intended, I wanted to refactor my service for educational purposes since I am new to Javascript/Typescript. The goal was to have a single function that can return either a list of students or details of a specific student based on the presence of an id parameter. This led to the creation of students-service-version2:
getStudents(id?: number): Observable<Student[]> {
if(id)
return this.httpClient.get<Student[]>(`${this.studentsUrl}${id}/`, this.baseService.httpOptions);
else
return this.httpClient.get<Student[]>(this.studentsUrl, this.baseService.httpOptions);
}
To handle the change in output type, I modified the code in component-version2:
ngOnInit(): void {
if(!this.student) {
this.studentsService.getStudents(this.id).subscribe(
(response: Student[]) => {
this.student = response[0] as Student;
},
error => console.log(error)
)
}
}
However, despite making these adjustments, the initialization does not set the "student" variable as expected. Despite trying different approaches like using pop()
method, the issue persists. It remains undefined after initialization, and I am unsure about the reason behind it.