My JSON response (from ASP.NET core Web API) looks like:
[
{
"pilot": {
"firstName": "TEST",
"lastName": "LAST",
"assignedFlight": "O_FLIGHT"
}
},
{
"pilot": {
"firstName": "First",
"lastName": "Last",
"assignedFlight": "M_FLIGHT"
}
}
]
My TypeScript interfaces look like:
pilot.ts
export interface Pilot {
firstName: string;
lastName: string;
assignedFlight: string;
}
commitment.ts
import { Pilot } from './pilot';
export interface Commitment {
pilot: Pilot;
}
And in my commitments.service.ts
@Injectable({
providedIn: 'root'
})
export class CommitmentsService {
private commitmentsApiUrl = 'http://localhost:55012/commitments';
constructor(private http: HttpClient) { }
getCommitments(): Observable<Commitment[]> {
return this.http.get<Commitment[]>(this.commitmentsApiUrl).pipe(tap(ev => console.log(ev)));
}
}
Finally, I subscribe to the observable in my component:
@Component({
selector: 'app-commitments',
templateUrl: './commitments.component.html',
styleUrls: ['./commitments.component.css']
})
export class CommitmentsComponent implements OnInit {
commitments: Commitment[];
constructor(private commitmentsService: CommitmentsService) { }
ngOnInit(): void {
this.commitmentsService.getCommitments().subscribe(commitments => this.commitments = commitments);
console.log(this.commitments); /* Undefined here??? */
}
}
For the life of me, I cannot figure out why the JSON is not being mapped when a nested interface is involved. this.commitments
in the component shows undefined
. I've run the JSON through a JSON validator/linter and it shows that it's valid. I know the answer is something simple that I am over-looking. Any ideas? Thanks!