robwormald / ng-universal-demo

256 stars 125 forks source link

How to override provider? #22

Open sebestindragos opened 7 years ago

sebestindragos commented 7 years ago

Hi! I have a service in my app that makes use of localStorage. I tried making use of provide with an InjectToken to override it on the server, but I can't think of a solution on how to do it.

AppModule looks like this:

imports: [
    BrowserModule.withServerTransition({
      appId: 'app'
    }),
],
providers: [
  {provide: LocalStorage, useValue: window.localStorage}
]

LocalStorage is an InjectToken instance export const LocalStorage = new InjectToken();

and in my server side code I have

app.engine('html', ngExpressEngine({
  baseUrl: nconf.get('hostname'),
  providers: [
     {provide: LocalStorage, useValue: {
      setItem() {},
      getItem() {},
      removeItem() {}
    }}
  ],
  bootstrap: [AppServerModuleNgFactory],
}));

ngExpressEngine

renderModuleFactory(setupOptions.bootstrap[0], {
  document: templateCache[filePath],
  url: options.req.url,
  extraProviders: setupOptions.providers
}).then(template => callback(null, template));

Running the app with this config, doesn't work, and I have no idea if this is even possible. Can providers be overriden from an outside module? Documentation seems to be pretty lacking on this subject.

The only way I can think of now, is to not import AppModule in AppServerModule, and make the AppServerModule basically a copy of AppModule with different imports and providers. But I'd like to avoid this method.

Any ideas? Thanks!

kkaabbaa commented 7 years ago

I had problems with localStorage. I solved them only so

if (typeof window! == 'undefined') {
        const token = localStorage.getItem ('token');
     }