window is undefined when used as useValue provider with Angular 4 AoT

假如想象 提交于 2019-11-28 12:30:33

I was having a similar problem but it was with a SignalrWindow. The concept and the error though was identical.

I then found this article here (https://blog.sstorie.com/integrating-angular-2-and-signalr-part-2-of-2/), and there were some comments at the bottom of the article that helped me solve the problem.

Basically, it boils done to using a factory method instead of a useValue in the providers. I'm not sure why it's a problem, but I do know that this approach solves the aot problem.

The steps to fix:

Create a function that is exported

export function windowFactory(): any {
    return window;
}

Then in the core module, in @NgModule in the providers you can do this:

...
providers: [
    { provide: SignalrWindow, useFactory: windowFactory }
  ]
...

Basically, you can rename the methods however you like (so, in your example it would be:)

export const windowProvider = { provide: windowToken, useFactory: windowFactory };

During AoT compilation, angular CLI statically analyses code too generate ngmodule.factory file. It sees "useValue" and check if static value is available and puts it into ngmodule.factory. During compile time, this value is not available, so it leaves that provider value and hence, it is returned as "undefined" when injected into constuctor.

However, "useFactory" is provided for very same purpose where you don't know your value until runtime.

Due to this, useValue is not working in your scenario, but "useFactory" will work.

Bottom line: When AOT compilation, Use "useValue" only if you have static value like constant string or number. Else use "useFactory" to return run-time calculated object/values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!