0

I'm using Angular 6. When i want to use route parameters, I use this code:

this.route.params.subscribe(params => {
    // use params now as a object variable
});

But I need to use parameters in service calling. Example I have a service for getting user info. And I call this service inside of resolver. If I want to use subscribe, I can not return service result:

resolve(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<any> {
    this.route.params.subscribe(params => {
        return this.FixturesService.getFixtures(params);
    });    
});

It's not working now. It says:

A function whose declared type in neither 'void' nor 'any' must return a value.

How can I return service result, inside of the resolve function with passing route parameters to the service that I called and return it to component?

Abdol Seed
  • 1,227
  • 1
  • 14
  • 23

1 Answers1

1

You can solve this by using switchMap to change your route params observable to the observable of your service:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
  return route.params.switchMap(params => this.FixturesService.getFixtures(params));
}

The service call will not be made until the params are resolved, and then subscribers will receive the result of the service call.

Thanks to @JBNizet for the correction.

Zircon
  • 4,677
  • 15
  • 32
  • If this.FixturesService.getFixtures() returns an Observable, it should in fact be switchMap(), not map(). And, @Sami, Don't use `any`. Use the correct type of the data that the service is returning. – JB Nizet Jun 19 '18 at 18:10
  • I tried map and switchMap but did not work. Same error: **vendor.js:32791 ERROR Error: Uncaught (in promise): TypeError: route.params.switchMap is not a function TypeError: route.params.switchMap is not a function** – Abdol Seed Jun 19 '18 at 18:21
  • @JBNizet What type should I use for objects? – Abdol Seed Jun 19 '18 at 18:22
  • You may need to import the operator for `switchMap`, but that might have changed in Angular 6 and I don't know on hand what is the appropriate way to do it. – Zircon Jun 19 '18 at 18:42
  • Actually, route here is of type ActivatedRouteSnapshot, not ActivatedRoute. So the params are accessible directly. `return this.FixturesService.getFixtures(route.params)`. https://angular.io/api/router/ActivatedRouteSnapshot#params – JB Nizet Jun 19 '18 at 19:05
  • But I have another problem. I'm using resolver and service for binding data before loading the route completely for angular universal. I want to bind XHR data to view when I try to open "view source" version in angular universal. – Abdol Seed Jun 20 '18 at 06:16