When compiling an Angular 4.0.2 application ahead-of-time, and defining a provider using useValue
import { OpaqueToken, Provider } from '@angular/core';
export const windowToken = new OpaqueToken('window');
export const windowProvider = { provide: windowToken, useValue: window };
and then using it like this
@NgModule({ providers: [windowProvider], ... })
export class AppModule {}
the compilation completes without errors but results in window
being undefined
when trying to inject it in the constructor:
constructor(@Inject(windowToken) window) {
window.navigator...
}
An error occurs during bootstrapping:
TypeError: Cannot read property 'navigator' of undefined
Upon examining the auto-generated app.module.ngfactory.js file, it becomes evident that window
is indeed undefined
:
...
import * as import39 from './window';
var AppModuleInjector = (function (_super) {
...
AppModuleInjector.prototype.createInternal = function () {
...
this._windowToken_26 = undefined;
this._SomeService_27 = new import16.SomeService(this._windowToken_26);
}
AppModuleInjector.prototype.getInternal = function (token, notFoundResult) {
...
if ((token === import39.windowToken)) {
return this._windowToken_26;
}
...
However, if the same service is used with useFactory
, everything works fine:
export function windowFactory() {
return window;
}
export const windowProvider = { provide: windowToken, useFactory: windowFactory };
What exactly causes the issue when using window
as a useValue
provider? Is it a common problem? Does this limitation apply to all global variables or all useValue
providers?