In my ngOnInit function (in vehicle.component.ts) I recieving data from server and then dispeching that array of vehicles to the Store. After that I subscribing to the store data to find the vehicle. But when I calling vehicle.find(), my template is already rendered with errors - of course no vehicle found... What should I do to fix this?
ngOnInit() {
let id = this._route.snapshot.params.id ? this._route.snapshot.params.id : null;
if(id){ // Передан id
this.newVehicle = false;
// Если не были загружены данные, загрузить
if (!this._vehicleService.dataIsLoaded){
this._vehicleService.getVehicles().subscribe(vehicles => {
this._store.dispatch({type: INIT_VEHICLES, payload: vehicles});
this.vehicles.subscribe(vehicles => {
this.vehicle = vehicles.find(item => item.id === Number(id))
});
})
} else {
this.vehicles.subscribe(vehicles =>
this.vehicle = vehicles.find(item => item.id === Number(id))
);
}
if(!this.vehicle)
console.error('No Vehicle found!');
} else { // id пустой, создаем новый объект
this.vehicle = new Vehicle(this.getLastVehicleId()+1, null, null);
}
}
My template (vehicle.component.html):
<h3>{{ vehicle.name }}</h3>
<div><label>Id: </label>{{ vehicle.id }}</div>
<div>
<label>Name: </label>
<input [(ngModel)]="vehicle.name" placeholder="name" />
</div>
<p>
<button (click)="saveVehicle()">Back</button>
<button class="abort" (click)="removeVehicle()">Remove</button>
</p>
Full source code is here: GitHub, last version running on GitHub Pages
PS
To reproduce the error you should navigate to vehicle info page and psess F5. Not reproducing on ghpages, it just crashing )