I am currently working with a model named "Professional" which includes a property that is another model called "Address":
'use strict';
import * as Address from './models/address';
export interface Professional {
id?: number;
name?: string;
address?: Address;
}
Here is the definition of the Address model:
'use strict';
export interface Address{
id?: number;
name?: string;
}
The challenge I'm facing is in the component that utilizes an instance of Professionals:
<input type="text" [(ngModel)]="professional.name">
<input [(ngModel)]="professional.address.id" class="form-control">
When retrieving an instance of a professional from a database and saving it in a variable called "professional", the property "name" is successfully set to the object's value. However, I encounter an error while accessing the "address" property:
EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in ./CreateProfessional class CreateProfessional - inline template:48:59 ORIGINAL EXCEPTION: TypeError: Cannot read property 'id' of undefined The TypeScript code contains the method to retrieve a professional instance:
import { Component, OnInit } from '@angular/core';
import { DefaultApi } from '../../../api/api/DefaultApi';
import {Professional} from '../../../api/model/Professional';
import {Address} from '../../../api/model/Address';
declare var $: any;
@Component({
selector: 'professionals',
styles: [require('./professionals.component.css').toString()],
template: require('./professionals.component.html'),
providers: [DefaultApi]
})
export class CreateEditProfessionalsComponent {
professional: Professional = {};
ngOnInit() {
this.onGet(1);
};
onGet = (id: number) => {
this._apiDentos.findProfessionalById(id.toString())
.subscribe(res => {
this.professional = res
},
console.error);
};
}
Is there a way to properly instantiate the "professional.address" property since it is an object? Should I create a separate variable and then assign the property value to it? What is the correct approach?
This is how the JSON data looks like:
{
"id":1,
"name":"1",
"address":{
"id":1,
"name":"fsda"
}
}