Vineet
Vineet

Reputation: 387

Angular 10 - What is a Error: R3InjectorError(AppModule)[Window -> Window -> Window]

I am trying to access the window object in Angular via a service that can be injected.

import { Injectable } from '@angular/core';

function _window():any {
  return window;
}

@Injectable({
  providedIn: "root"
})
export class WindowRef {
  get nativeWindow():any{
    return _window()
  }
}

I tried to create a injectable service and trying it to include in App Module but looks like there is some error. Tried to add as

@Injectable({
  providedIn: "root"
})

In service file and also tried the other way around in app.module as

import { WindowRef } from './_windowRef.service'; 

and then

providers: [WindowRef], 

ERROR Error: R3InjectorError(AppModule)[Window -> Window -> Window]: NullInjectorError: No provider for Window!

. this is the link to stackblitz - code.

Can you please let know as to what I am missing here or how can I get rid of the error.

Upvotes: 1

Views: 5041

Answers (2)

Vineet
Vineet

Reputation: 387

got a easy way out. Directly provide the window object as

providers: [
    { provide: Window, useValue: window }
]

and access anywhere as

constructor(private window: Window) {
    // ...
}

Upvotes: 0

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15219

You're making a WindowRef service available, but how is Angular supposed to know to use it for Window? WindowRef != Window.

The usual way is to use a factory provider with an injection token like this:

export const WINDOW = new InjectionToken<Window>('window');

export const WindowProvider: FactoryProvider = {
  provide: WINDOW,
  useFactory: getWindow
};

export function getWindow(): Window {
  return window;
}

Then provide it in your module:

providers: [ WindowProvider ]

And use @Inject for your component:

constructor( @Inject(WINDOW) private window: Window )

Upvotes: 1

Related Questions