I have a service http which loads (and puts) data to/from API. In this case I need to get data from server and show them in template.
This is my code
export class RouteDetailComponent implements OnInit{
public routeId:number;
public route:Route;
public actUrl: string;
ngOnInit() {
this.routeId = this.activateDroute.snapshot.params['id'];
let data;
this.httpService.getRoute(this.routeId)
.subscribe(
(response: Response) => {
data = response.json().data;
this.route = new Route(
data.route_id,
data.route_name,
data.user_id,
data.first_name+" "+data.last_name,
data.tags,
data.added,
data.last_changed,
data.geojson,
data.visible,
data.description,
data.reviews,
data.route_length.toPrecision(3)
);
console.log(this.route);
},
(error) => console.log(error)
);
}
}
The route object is just object storing information of route (Some constructor, method parsing input data etc).
In template I'm using route object like <h4>{{this.route.routeName}}</h4>.
When I try to run this code I get many errors telling me Im trying to access property of undefined.
I think It's becouse subscribe is async event and html is rendered right after NgOnInit. However I do not know how to handle this. I would like to add some loading to the template before It's loaded from API and then show user that data.
Can anyone tell me how to do it, please?
*ngIf="!!route"