30 seconds of angular
Star
✨✨ New to Angular? Check out interactive Angular Codelab ✨✨

Window Location injection

For testing purposes you might want to inject window.location object in your component.
You can achieve this with custom InjectionToken mechanism provided by Angular.

export const LOCATION_TOKEN = new InjectionToken<Location>('Window location object');
    
    @NgModule({
      providers: [
        { provide: LOCATION_TOKEN, useValue: window.location }
      ]
    })
    export class SharedModule {}
    
    //...
    
    @Component({
    })
    export class AppComponent {
      constructor(
        @Inject(LOCATION_TOKEN) public location: Location
      ) {}
    }
    

Links