1

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

2
  • Trust me on this; you dont want to subscribe inside of a service. Commented Dec 22, 2017 at 15:34
  • Hi Jota.Toledo, why not? Commented Dec 22, 2017 at 16:23

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry it doesn't work. Property 'map' does not exist on type 'Observable<Object>'
try not returning the observable from the service...did you import the operator? import 'rxjs/add/operator/map'; getStandings() { return this.http.get('localhost:8080/api/fixtures/standings')}
Oh was that. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.