After calling my ASP.NET Core Web API, the JSON response appears as:
[
{
"driver": {
"firstName": "TEST",
"lastName": "LAST",
"assignedRoute": "O_ROUTE"
}
},
{
"driver": {
"firstName": "First",
"lastName": "Last",
"assignedRoute": "M_ROUTE"
}
}
]
The TypeScript interfaces I used are as follows:
driver.ts
export interface Driver {
firstName: string;
lastName: string;
assignedRoute: string;
}
schedule.ts
import { Driver } from './driver';
export interface Schedule {
driver: Driver;
}
In schedule.service.ts:
@Injectable({
providedIn: 'root'
})
export class ScheduleService {
private scheduleApiUrl = 'http://localhost:55012/schedule';
constructor(private http: HttpClient) { }
getSchedule(): Observable<Schedule[]> {
return this.http.get<Schedule[]>(this.scheduleApiUrl).pipe(tap(ev => console.log(ev)));
}
}
To display the data, I subscribed to the observable in my component:
@Component({
selector: 'app-schedule',
templateUrl: './schedule.component.html',
styleUrls: ['./schedule.component.css']
})
export class ScheduleComponent implements OnInit {
schedule: Schedule[];
constructor(private scheduleService: ScheduleService) { }
ngOnInit(): void {
this.scheduleService.getSchedule().subscribe(schedule => this.schedule = schedule);
console.log(this.schedule); /* Why is it showing undefined here??? */
}
}
I'm puzzled as to why the mapping of JSON data with a nested interface is not working. The component displays undefined
for this.schedule
. I've validated the JSON and it's correct. Any insights on what could be the issue? Thank you!