How to retrieve a route param using Injector.get(ActivatedRoute)?

I'm new to Angular. My goal is to have a BaseDetailComponent which can be extended by "detail" components (those which show a single data object's fields). Since the parent class' constructor will receive a service instance and other params, I can't use normal dependency injection in the constructor. Therefore, I need to manually inject the application injector in BaseDetailComponent. I tried the code below. There is an InjectorManager, which has its injector set by the global AppModule. Then BaseDetailComponent retrieves InjectorManager's injector and uses it to get the app's ActivatedRoute instance. But, for some reason, activatedRoute.snapshot.params.id is undefined. And this is my issue. I need to access route params on a class where ordinary constructor dependency injection is unavailable.

export class InjectorManager {

  private static _injector: Injector;

  static get injector(): Injector {
    return this._injector;
  }

  static set injector(value: Injector) {
    this._injector = value;
  }
}

export class AppModule {

  constructor(
    injector: Injector
  ) {
    InjectorManager.injector = injector;
  }
}

@Component({template: ''})
export class BaseDetailComponent {

  protected activatedRoute: ActivatedRoute;

  constructor(
    private service: BaseService<DtoType>
  ) {
    this.activatedRoute = InjectorManager.injector.get(ActivatedRoute);
  }

  ngOnInit() {

    this.service.findById(this.activatedRoute.snapshot.params.id)
      .subscribe(...);
  }
}

This is a similar question as Parent components gets empty Params from ActivatedRoute.

The Angular documentation for ActivatedRoute states (my emphasis):

Contains the information about a route associated with a component loaded in an outlet.

There is also an issue of feature request on Angular's GitHub repo asking for a solution, that states (my emphasis):

When using a parametrized route which targets a component, only this component can access those parameters.

Thus, you are encountering an expected behavior. A comment on that issue states that each component receives its own ActivatedRoute (it does not work as singleton like other injected classes).

On that same GitHub issue, the proposed solution is to inject a Router and check for the NavigationEnd events:

router.events.filter(e => e instanceof NavigationEnd).forEach(() => {
  // inspect the state on router.routerState
})

For a complete example check the file src/app.ts on this plunkr provided by @brandonroberts on the GitHub issue: http://plnkr.co/edit/pHd89K?p=preview

Accessing Route Parameters with ActivatedRoute vs , How to retrieve a route param using Injector.get(ActivatedRoute)? - angular But , for some reason, activatedRoute.snapshot.params.id is undefined. And this is� params—An Observable that contains the required and optional parameters specific to the route. Use paramMap instead. queryParams—An Observable that contains the query parameters available to

Firs you can inject ActivatedRoute just by placing it in the constructor params.

constructor(
    private service: BaseService<DtoType>,
    protected activatedRoute: ActivatedRoute;
) {}

Second you have to subscribe to this.activatedRoute.params as it can change after the component is initialized:

this.activatedRoute.params.pipe(switchMap(({id}) => this.service.findById(id)).Subscribe(...)

ActivatedRoute, We often need to get a route parameter so we can make a component dynamic based on that parameter. In this guide, we'll learn how to extract� Since you want the current route params, instead of activatedRoute.snapshot, you should be subscribing to activatedRoute.params. It will give you the latest and updated value of the current route params. Your service method should not be responsible for getting the id from the ActivatedRoute. It should be the responsibility of your Component.

To get route params subscribe on activatedRoute.params.subscribe((data) => {ur code}) Here the data will contain the params. suppose your registration is path : abc/:id Then the params will conatin id property.

How To Get Route Path Parameters In Non-Routed Angular , Angular Dependency Injection Provides access to information about a route associated with a component that is loaded in an outlet. Getting route information ActivatedRoute) { const id: Observable<string> = route.params.pipe (map(p� The Angular adds the map all the route parameters in the ParamMap object, which can be accessed from the ActivatedRoute service. The ParamMap makes it easier to work with parameters. We can use get or getAll methods to retrieve the value of the parameters in the component.

RouterTestingModule should provide a way to set up snapshot data , As it turns out, getting route path parameter in a non-routed That way we can inject ActivatedRoute and retrieve the path params without any issue! how to use new better Angular 6+ dependency injection mechanism with� ActivatedRoute works for components loaded via router-outlet. From docs - it: Contains the information about a route associated with a component loaded in an outlet. I don't think you can use it in components that are not loaded in an outlet. It also doesn't work in base classes your component extends.

Dependency Injection and Routing, (TestBed describes one injector, and we need a tree of injectors to do that). createComponent(ComponentB); // this gets the activated route for ComponentA tests simpler (similar to the one I defined in the comment above)? the root to this route ( ActivatedRouteSnapshot[] ); Route parameter map� Depending on the version of Angular (4+) you are using, you need access query params via an observable on ActivatedRoute called queryParamMap: queryParamMap An Observable that contains a map of the query parameters available to all routes. The map supports retrieving single and multiple values from the query parameter.

Passing Complex Data Through The Angular Router With NativeScript, A class with Injectable by itself will not be used in dependency injection. The injector will look up this key when trying to find a dependency to inject. The activated route is the current route path and parameters as an injected service. This observable allows the new parameters and queryParmeters to be retrieved. The parent of this route in the router state tree. firstChild: ActivatedRoute | null: Read-Only. The first child of this route in the router state tree. children: ActivatedRoute[] Read-Only. The children of this route in the router state tree. pathFromRoot: ActivatedRoute[] Read-Only. The path from the root of the router state tree to this route.

Comments
  • Instead of using activatedRoute.snapshot, you can try subscribing activatedRoute.params.
  • I tried it, but it did not work. See below.
  • Because BaseDetailComponent is gonna be extended, the constructor cannot have and ActivatedRoute parameter. Otherwise child classes would have to send that, leading to unnecessary repeated code. For some reason, your suggestion (pipe and switchMap over params Observable) is not working. this.activatedRoute.params .pipe( switchMap((params: Params) => { return this.service.findById(params['id']); })) .subscribe(...
  • Are you sure that you need to retrieve route params? Maybe you mean query params? How does your request look like?
  • Stanisalv, thanks for staying with me against this mistery! My request is an HTTP GET against localhost:4200/restaurant-detail/3 . I'm trying to retrieve that "3", but I cannot use regular Angular dependenty injection (constructor parameter) because it's about generic components to be extended.
  • seems like a route parameter, but what is your routing configuration then?
  • I tried, but for some reason it does not work. ` this.activatedRoute.params .pipe( switchMap((params: Params) => { return this.service.findById(params['id']); })) .subscribe(`