11

So I implemented a resolver in angular 5:

@Injectable()
export class AppResolver implements Resolve<MyComplexObject []> {
  constructor(private myService: MyService) {

   }
   resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<MyComplexObject[]> {
     return this.myService.getMyApi(myOption); // my option is a string
   }
}

right now myOption is a hardcoded string and i want to change that

in my routing module i have:

resolve: {
  myResolver: AppResolver
}

I suppose maybe here I should specify the value of myOption string but how?

or better yet where I actually call the resolver

this.route.data.map(data => data.myResolver).subscribe(
  result => {
    // do something with the result (specify who the myOption is?? How)
  }
);

the parameter is not necessarily visible in the browser :

it will be part of the url: /.../.../myString/..

but it's not introduced by a param : url: /..&myParam=paramValue

so I can t use myParam to identify it from the url and replace it

Strider
  • 3,539
  • 5
  • 32
  • 60
annepic
  • 1,147
  • 3
  • 14
  • 24
  • which value you want to set to that `myOption` – Sravan May 17 '18 at 06:28
  • so it should be dynamically assigned to an enum value because i should use the same resolver in multiple places (each time with a different resolve param) and i don't want to duplicate the resolver code. i hope this helps clarify – annepic May 17 '18 at 06:36
  • yes then you can send a value through `data`, while defining the routes – Sravan May 17 '18 at 06:39
  • any advice on how i would do that pls? – annepic May 17 '18 at 06:40
  • yeah, I m adding code – Sravan May 17 '18 at 06:40
  • i tried adding this alert(route.params['myParam']); - myParam is the exact param name as defined within my api; i put it right before the return statement in the resolver. it returned an undefined. – annepic May 17 '18 at 06:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/171210/discussion-between-sravan-and-annepic). – Sravan May 17 '18 at 06:43

1 Answers1

30

Here is an example to send data to resolver,

Route configuration:

{
  path: 'project/:id',
  component: ProjectComponent,
  resolve: { data: AppResolver },
  data: { resolvedata: 'myValue' }
}

Resolver:

@Injectable()
export class AppResolver implements Resolve<MyComplexObject []> { 
  constructor(private myService: MyService, private router: Router) {} 
  resolve(route: ActivatedRouteSnapshot): Observable<MyComplexObject[]>|boolean { 
    let myParam = route.data['resolvedata']; 
    console.log(myParam); 
  } 
}
Sravan
  • 18,467
  • 3
  • 30
  • 54