angularangular-di

useFactory vs useValue with AoT compilation


I use window.location to setup for injectable. In my module near imports I define 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 do I get undefined with useValue and true with useFactory?


Solution

  • My guess is that AoT statically analyses your code outside of the NgModule structure. So it sees window.location.search.includes and executes this ahead of time. But at compilation time, this will obviously return undefined. In the case of using a factory, it will not try to execute the body ahead of time, only at run-time.

    It's one of the (many) pitfalls of AOT. Always try to have every symbol statically analyzable