How to insert a window in Angular 2.1.0

In earlier versions of RC Angular 2, I managed to add a window object by adding

{provide: Window, useValue: window}

To an array of suppliers.

Since upgrading to the latest stable version of Angular 2 (2.1.0) now causes a console error

compiler.umd.js: 14268Uncaught Error: cannot resolve all parameters for LoginComponent: (AuthService, UserMessagesService ,?).

What? in the parameter list where I am trying to enter a Window object.

+8
source share
3 answers

Try:

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
   { provide: "windowObject", useValue: window}
  ]
})

HomeModule export class {}

in your component:

constructor(@Inject("windowObject") window: Window})
+15
source

For it to work with AOT, you need to use useFactory instead of useValue:

export function windowFactory() {
  return window;
}

module:

providers: [
   { provide: 'window', useFactory: windowFactory }
]

component:

constructor(@Inject('window') window: Window})
+8
source

I used WindowJavaScript as the provided, not the string. Seems to work:

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

Consumer:

@Injectable()
export class LocalStorageService {
    constructor(
        private theInjectedWindow: Window,
    ) {}
}s
0
source

Source: https://habr.com/ru/post/1658712/


All Articles