job.answiz.com
  • 1
Votes
name
name Punditsdkoslkdosdkoskdo

Getting error when trying to subscribe to function in ngOnInit

I am getting error "Cannot read property 'name' of undefined" I have a simple api that returns a Vehicle, which has these fields

    public int Id {get ;set;}
    public int ModelId { get; set; }

    public KeyValuePairResource Model { get; set; }
    public KeyValuePairResource Make { get; set; }
    public bool IsRegistered { get; set; }

    public Contact ContactInformation { get; set; }

    public DateTime LastUpdate {get; set;}
    public ICollection<KeyValuePairResource> Features  { get; set; }`

Now, In the angular front end, I have a simple get method that calls this api endpoint

getVehicle(id) {
   return this.http.get('/api/vehicles/'+ id);


}

in my angular component onInit function i am doing

ngOnInit() {

this.makes = this.vehicleService.getMakes();
this.features = this.vehicleService.getFeatures();
// this.vehicle is defined as any 
this.vehicleService.getVehicle(this.vehicle.id)
.subscribe(res=> { this.vehicle = res ;});

}

and finally the code where the program fails seems to be in the HTML

<div class="form-group"><label for="ContactName">Name</label>
        <input id= "ContactName" required #name="ngModel" type="text" class="form-control" [(ngModel)] = "vehicle.ContactInformation.name " name = "name"></div>
    <div class="alert alert-danger" *ngIf="!name.valid && name.touched">Please enter Name</div>

I have seen similar problems on stack, but none of them have actually solved my problem. I know that the function is asynchronous and the webpage tries to load it before the async function returns completely. But i have other parts in the code where i try to access things like in

<div *ngFor="let f of features"class="checkbox">
<label for="feature{{f.id}}" (change) = "onFeatureToggle(f.id , $event)">
    <input type="checkbox" id="feature{{f.id}}">{{f.name}}
</label>

and that doesn't seem to crash. I am really confused. I think i have given what is necessary for this problem, but please tell me if i need to provide more code. The worst part is, i actually got it to work by accident, and the code in onInit didn't look any different.

From what I can tell, your HTML is trying to access the ContactInformation property of this.vehicle, but the call to your API hasn't returned it yet...meaning your template is loading faster than the API call takes to get the data. Which is normal.

There are a few things you could do. The easiest is to use the defaulting mechanism Angular provides in the template binding, which is by doing this: [(ngModel)]="vehicle?.ContactInformation?.name". Those question marks will overload the property with defaults if they are not defined. It's sort of like doing this in JavaScript: ((vehicle || {}).ContactInformation || {}).name || ''

  • 0
Reply Report


Related Questions

Trending Tags