UseFactory vs useValue with AoT compilation
I am using a window.location
setup for injection. In my module, next to the import, I define a variable
const flag = window.location.search.includes('flag');
...
{ provide: FLAG, useValue: flag },
and it works as expected with JIT compilation But when I switch to AoT it breaks
useFactory
works in both cases
export function flagFactory() {
return window.location.search.includes('flag');;
}
...
{ provide: FLAG, useFactory: flagFactory },
Why am I getting undefined
with useValue
and true
using useFactory
?
source to share
I am assuming that it AoT
statically parses your code out of structure NgModule
. Thus, he sees window.location.search.includes
and does it ahead of time. But at compile time this will obviously return undefined
. If used, factory
it will not try to execute the body ahead of time, only at runtime.
This is one of the (many) AOT pitfalls. Always try to have each character statically analyzed
source to share