phenomnomnominal / angular-2-local-storage

LocalStorageService for Angular 2 with the same API as angular-local-storage
MIT License
93 stars 49 forks source link

Setting prefix using a variable with aot enabled fails #47

Open tobigit opened 7 years ago

tobigit commented 7 years ago

Thanx for this great plugin!

I have a question. I am using angular 4.3.5 with angular cli 1.3.2 and compile my code with aot enabled. How can i use a variable stored in global window-variable for prefix?

import { LocalStorageModule } from 'angular-2-local-storage';

// window.ownVariables.var1 is initialized in index.html !
const myVariable = `my-app-${window.ownVariables.var1}`;

@NgModule({
    imports: [
        LocalStorageModule.withConfig({
            prefix: `my-app-${myVariable}`,
            storageType: 'localStorage'
        })
    ],
    declarations: [
        ..
    ],
    providers: [
        ..
    ],
    bootstrap: [AppComponent]
})
export class AppModule {}

The variable myVaraible is undefined at compile time of aot. Do you have any ideas to solve this problem? Is there a possibility to set the prefix in another way?

ngiebel commented 6 years ago

I didn't test this, but something along the lines of the following should work.

import { LocalStorageService } from 'angular-2-local-storage';

export let localStorageConfigFactory = () => {
    return {
        prefix: `my-app-${window.ownVariables.var1}`,
        storageType: 'localStorage'
    }
}

export let localStorageConfigProvider = {
  provide: 'LOCAL_STORAGE_SERVICE_CONFIG',
  useFactory: localStorageConfigFactory
};

@NgModule({
    imports: [],
    declarations: [],
    providers: [
        localStorageConfigProvider,
        LocalStorageService //not required if the service is made 'shakeable' 
    ],
    bootstrap: [AppComponent]
})
export class AppModule {}