问题描述:

I've got a model "Profesional" that has a property that is another model "Address":

 'use strict';

import * as Address from './models/address';

export interface Profesional {

id?: number;

name?: string;

address?: Address;

}

and the other model:

 'use strict';

export interface Adress{

id?: number;

name?: string;

}

The issue I'm having is in the component that uses an instance from Profesionals:

 <input type="text" [(ngModel)]="profesional.name">

<input [(ngModel)]="profesional.address.id" class="form-control">

When I get from a dada base an instance of profesional, saved in a variable called profesional, the property name is set with the value from the object. But the adress gives me an error:

EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in ./CreateProfetional class CreateProfetional - inline template:48:59 ORIGINAL EXCEPTION: TypeError: Cannot read property 'id' of undefined

The ts just have the method to get a profesional instance:

import { Component, OnInit } from '@angular/core';

import { DefaultApi } from '../../../api/api/DefaultApi';

import {Profesional} from '../../../api/model/Profetional';

import {Address} from '../../../api/model/Address';

declare var $: any;

@Component({

selector: 'profesionales',

styles: [require('./profesionales.component.css').toString()],

template: require('./profesionales.component.html'),

providers: [DefaultApi]

})

export class CrearEditarProfesionalesComponent {

profesional: Profesional = {};

ngOnInit() {

this.onGet(1);

};

onGet = (id: number) => {

this._apiDentos.findProfesionalById(id.toString())

.subscribe(res => {

this.profesional = res

},

console.error);

};

}

How can I instantiate this property "profesional.adress" that is an object? It is posible, or I must create a simple variable and then assign the property value to it? What it the correct way to do this?

This is the json:

{

"id":1,

"name":"1",

"address":{

"id":1,

"name":"fsda"

}

}

网友答案:

First of all, note that in your Professional interface, the type of address should be changed from string to Address. Now, you need to initialize at least the sub-objects so you will not get the exception:

profesional: Profesional = <Profesional>{ 'address' : {} };

Better option would be to initialize all properties, but that depends on the domain.

网友答案:

Wherever you make a Professional, you must include an instantiation of Address. So:

profesional: Profesional = { address: {} };

Note that your typing of address is also wrong - it should be the interface type, not a string. Given the way you intend to use it, you may want to remove the question mark from its definition too. (OR, instead of all this, you can enclose that input with:

<div *ngIf="professional.address">

...and instantiate the address somewhere else.)

相关阅读:
Top