Angular 2 : How to get params on resolve

angularangular2-routing

Routs Strategy:

export const routes = [
{
    path       : 'rto-activation/:id',
    component  : RtoActivationComponent,
    resolve  : {
        'singleRto': SingleRtoResolve
    },
    children   : [
        {path: 'start', component: ActivationStartComponent},
        {path: 'warning', component: WarningComponent},
        {path: 'confirm', component: ConfirmRtoDetailsComponent},
        {path: 'ldWaiver', component: LDWaiverComponent},
        {path: 'payment-schedule', component: PaymentScheduleComponent},
        {path: 'user-reference', component: ReferenceComponent}

    ]
}

SingleRtoResolve:

constructor(private router: Router,
            private route: ActivatedRoute) {
}

resolve() {
    var self = this;
    return new Promise((resolve, reject) => {
        self.subscription = self.route.params.subscribe(
            (param: any) => {
                let id = param[ 'id' ];
               self.rtoService.getRto(null, +id)
                .then((res: any) => {
                    resolve(res)
                })

            });
    });
    }

I Know: We usually get params from ActivatedRoute service.

Question: Can i get params from Router service.

Brief: Trying to get route params on Resolve Injectable because on that stage route is not actived and i am unable to get params.

Usecase: When a user opens any child routes(implicity and explicitly)with some (:id) so data should be resolved in parent routes.

Get Params successfully when route is actived in any child component:

ngOnInit() {
let self          = this;
this.subscription = this.route.params.subscribe(
    (param: any) => {
        let id = param[ 'id' ];
        self.rtoService.getRto(null, +id)
            .then((res: any) => {

            })

    });
}

Best Answer

Your SingleRtoResolve should implements Resolve<T>. Then you'll just need your data service (RtoServicei guess) in your constructor() {}. No need for the Router or the ActivatedRoute here since your resolve() will get a ActivatedRouteSnapshot and a RouterStateSnapshot. So the resolve() will look smth like that:

  resolve(
    route: ActivatedRouteSnapshot, state: RouterStateSnapshot
  ): Promise<any> {
    return ...
  }

..and you can just use route.params['id']to get your id.


Edit: You can also check the docs for the Resolve