When Angular 4.0.2 application is compiled ahead-of-time, and the provider is defined as useValue
import { OpaqueToken, Provider } from '@angular/core';
export const windowToken = new OpaqueToken('window');
export const windowProvider = { provide: windowToken, useValue: window };
and used like
@NgModule({ providers: [windowProvider], ... })
export class AppModule {}
it compiles ok but results in window
being undefined
when injected as
constructor(@Inject(windowToken) window) {
window.navigator...
}
The error is thrown on bootstrapping:
TypeError: Cannot read property 'navigator' of undefined
On a closer look at auto-generated app.module.ngfactory.js it appears that it 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;
}
...
When the same service is used as useFactory
, everything is ok:
export function windowFactory() {
return window;
}
export const windowProvider = { provide: windowToken, useFactory: windowFactory };
What exactly is wrong with using window
as useValue
provider here? Is it a known pitfall? Does this limitation apply to all globals or all useValue
providers?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…