在我的ngOnInit函数中(在vehicle.component.ts中)我从服务器接收数据,然后将该数组车辆分散到商店。之后,我订阅商店数据以找到车辆。但是当我打电话给 vehicle.find()时,我的模板已经呈现错误 - 当然没有找到车辆......我该怎么做才能解决这个问题?
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);
}
}
我的模板(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>
完整的源代码在这里:GitHub, 最后一个版本正在运行on GitHub Pages
PS
要重现错误,您应该导航到车辆信息页面和psess F5。 没有在ghpages上复制,它只是崩溃)