I am new to Angular 5 and was able to create view with access to service methods using subscribe but encounter problem in delay in render. The user see first "undefined" string and after 0.5 sec it change to the correct value.
Here is the .ts file for the component:
public trips: Trip[];
public numberOfUsers : Map<string, number> = new Map<string, number>();
constructor(private tripService: TripService) { }
ngOnInit() {
this.getTrips();
}
getTrips() {
this.tripService.getTripForMe().subscribe(
data => { this.trips = data;},
err => console.error(err),
() => this.initNumberOfUsers()
);
}
initNumberOfUsers() {
for (let i = 0; i < this.trips.length; i++) {
let count;
this.tripService.getNumberOfUsers().subscribe(
data => { count = data},
err => console.error(err),
() => this.numberOfUsers.set(this.trips[i].id, count)
);
;
}
}
getNumberOfUsers(data) {
return this.numberOfUsers.get(data.id);
}
The method initNumberOfUsers is called after the first subscribe finish which is good, but the getNumberOfUsers(data) called probably before and get "undefined".
Here is the relevant part from the template ("data" is current value of a ngFor loop):
<span [innerText]="getNumberOfUsers(data)"></span>
Is there a way to make sure that both subscribe methods are sequentially finalized before rendering ?
UPDATE
I was able to create a resolver and the concole show the object but, I have difficulties to pass the data to the component.
Reolver code:
import { Injectable } from '@angular/core';
import { Router, Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Trip} from ....
import { TripService } from .....
import { Observable } from 'rxjs/Rx';
@Injectable()
export class TripsResolve implements Resolve<Trip[]> {
public trips: Trip[];
constructor(private service: TripService) {}
resolve(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot) {
this.service.getTrips().subscribe(
data => { this.trips = data },
err => console.error(err),
() => console.log(this.trips)
);
return this.trips;
}
}
From route
resolve: {
trips: TripsResolve
}
From module
providers: [
...
TripsResolve,
...
Data is not pass/not avilavle in the component:
import { Component, OnInit } from '@angular/core';
import { Trip } from ...
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: ...
templateUrl: ...
styleUrls: ...
})
export class MyComponent implements OnInit {
public trips: Trip[];
constructor(private route: ActivatedRoute,
private router: Router) {
}
ngOnInit() {
this.route.data.forEach(data => {
this.trips = data.trips;
console.log(this.trips); //can't see it
});
}
}
Any idea how can I access/retrieve the data in the component ?