In an angular 5 project I want to execute a resolver before the view is loaded. The problem is the data I want to return from the resolver is depending on an observable. This is the code:
Resolver:
@Injectable()
export class PlayersResolver implements Resolve<any> {
constructor(private playersSrv: PlayersService) {
this.playersSrv.getStandings();
}
resolve() {
return this.playersSrv.standings$;
}
}
Service used by the resolver:
@Injectable()
export class PlayersService {
standingsSubject = new ReplaySubject<any>();
standings$ = this.standingsSubject.asObservable();
constructor(private http: HttpClient) {}
getStandings(): void {
this.http.get('http://localhost:8080/api/fixtures/standings')
.subscribe((response: any) => {
this.standingsSubject.next(response);
});
}
}
With this code when trying to navigate to the view anything is displayed. Any idea about how can I implement the resolve to get the data in my component?
Thanks
1.Return observable from the service function. 2.Remove subscribe from the service. 3.Just call the service function in resolve method that return the call to the service function inturn which returns an observable
resolve():observable<any>{
return this.playersSrv.getStandings().map((data)=>{//do something with data})
}
4.Resolve guard automatically subscribes to the service call and next route is loaded only when its resolved