resolver with parameter on resolve method

annepic picture annepic · May 17, 2018 · Viewed 8.7k times · Source

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

Answer

Sravan picture Sravan · May 17, 2018

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); 
  } 
}