Search code examples
angularangular-routingangular-resolver

angular router resolver - get params from parent on reload


I have a route like this, with a resolver for a child route.

 {
        path: 'organizations/:oid',
        component: AdminOrganizationComponent,
        children: [
          {
            path: 'profile',
            component: AdminOrganizationProfileComponent,
            resolve: { organization: OrganizationResolver }
          },
          { path: '', redirectTo: 'profile', pathMatch: 'full' }
        ]
      },

The resolver looks like this

@Injectable()
export class OrganizationResolver implements Resolve<Observable<Organization>> {
  private activeOrganization: Organization;
  constructor(private route:ActivatedRoute) {}

  setUser(organization: Organization) {
    this.activeOrganization = organization;
  }

  resolve() {
    return of(this.activeOrganization);
  }
}

Before I navigate to the route, I use the service to set the selected organization.

  edit(organization) {
    this.organizationResolver.setUser(organization);
    this.router.navigate(['/admin/organizations', organization.id]);
  }

So far it works just as intended, I can use snapshot.data to get the selected organization.

Now when I reload the route

/organizations/12345/profile

I want the resolver to check if there is a activeOrganization stored. If not, it is supposed to retrieve it via a http.get with the 12345 as id.

My problem is that i don't know with which tool I can retrieve the params. Normally in a component I can simple use activatedRoute.parent.params But in this case the injected activatedRoute.parent is null.

I figured that since I've provided the resolver in root, parent=null would make sense but logging out the snapshot I'm getting null in parent as well as firstChild...


Solution

  • ActivatedRouteSnapshot Contains the information about a route associated with a component loaded in an outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router state tree.

    import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
    
      resolve(route: ActivatedRouteSnapshot) {
        let id: any = route.params['id'];
      }