1

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 )

Anton Pegov
  • 1,413
  • 2
  • 20
  • 33
  • 1
    Possible duplicate of [Observable type error: cannot read property of undefined](https://stackoverflow.com/questions/34734671/observable-type-error-cannot-read-property-of-undefined) – AT82 May 31 '17 at 17:27
  • My question is more about @rxjs/store. – Anton Pegov May 31 '17 at 17:37
  • Yes, I've fix it by adding
    wrapper, and opening this flag after recieving data from the store. But I'm not shore it is the right way...
    – Anton Pegov May 31 '17 at 18:00

0 Answers0