Closed magnattic closed 4 years ago
The above code should have always thrown an exception since you are using a "variable" which doesn't exists, irreverent if the provider is overridden or not since you are referencing a variable which doesn't exist and hence it will throw an exception during the parsing phase.
There are three ways how you can make this work;
1) You can define a global window
mock. Example in your server.ts
you have global['window'] = {};
2) Instead of useValue
use useFactory
and wrap the variable in an arrow function Ex:
{ provide: LOCAL_STORAGE, useFactory: () => window.localStorage }
3) Verify that the window exists
{ provide: LOCAL_STORAGE, useValue: typeof window !== 'undefined' && window.localStorage }
Thanks, I landed on the useFactory
solution.
This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.
Bug Report
What is the expected behavior?
I have providers in my AppModule that access
window
. When I overwrite those providers in the AppServerModule, I expect that there will be no errors duringnpm run serve:ssr
.What is the current behavior?
This worked in the past version, but does not work anymore in Angular 9. The following errors occurs when I build and run the code as seen below.
The error shows that window is being accessed in the AppModule providers, although I have overwritten those providers. So I would expect that the providers should not be called.
What modules are related to this issue?
Minimal reproduction with instructions:
Add the following code:
local-storage.ts
app-module.ts
app-server-module.ts
What is the use-case or motivation for changing an existing behavior?
I want to write consistent code in both browser and SSR when accessing stuff like LocalStorage or window without using if/else.
Environment:
@nguniversal versions
Package Version
@angular-devkit/architect 0.900.0-next.11 @angular-devkit/build-angular 0.900.0-next.11 @angular-devkit/build-optimizer 0.900.0-next.11 @angular-devkit/build-webpack 0.900.0-next.11 @angular-devkit/core 9.0.0-next.11 @angular-devkit/schematics 9.0.0-next.11 @ngtools/webpack 9.0.0-next.11 @nguniversal/common 9.0.0-next.5 @nguniversal/express-engine 9.0.0-next.5 @schematics/angular 9.0.0-next.11 @schematics/update 0.900.0-next.11 rxjs 6.5.3 typescript 3.5.3 webpack 4.41.1