angularangular-routinginjectable

How do I get an instance of Angular router without injecting it?


Usually I'd go like this in my component.

import { Router } from "@angular/router";

@Component({ ... })
export class CompyTheComponent {
  constructor(private router: Router) { 
    console.log(router.url);
  }
}

What if I want to obtain a reference of it without injecting it? I've tried to create it but died on all the parameters I couldn't figure out. Ans since it's not the usual (nor recommended) way to approach it, there's not much googlearch on it.

let routy : Router = new Router(...);

Solution

  • Make a file called injector.ts with the following code:

    import { Injector } from "@angular/core";
    
    let appInjectorRef: Injector;
    
    export function appInjector (injector?: Injector): Injector {
        if (!injector) {
            return appInjectorRef;
        }
        appInjectorRef = injector;
        return appInjectorRef;
    }
    

    Then in your main.ts:

    bootstrap([...]).then((appRef: { injector: Injector }) => appInjector(appRef.injector))
      .catch((err: Error) => console.error(err));
    

    Then you can use it as:

    const router: Router = appInjector().get(Router);
    

    In any case, I'd recommend dependency injection over this.