Ionic conditionally add service provider

Viewed 420

What I wanna achieve is add providers conditionally, as follow:

made an interface:

export interface StorageInterface {
    Storage(): any;
    SwitchStorage(isLocal: boolean): void;
    ClearStorage(): void;
    Setter(key: string, value: any): void;
    Getter(key: string): any;
}

then made a class to implement it:

export class IonicStorage implements StorageInterface {


    get User(): User {
        return {};
    }
    set User(value: User) {

    }
    constructor( @Inject(forwardRef(() => Storage)) private storage: Storage) {

    }

    Storage() {
        return this.storage;
    }

    SwitchStorage(isLocal: boolean): void {

    }
    ClearStorage(): void {
        this.storage.clear();
    }

    Setter(key: string, value: any): void {

    }
    Getter(key: string) {

    }
}

then a module to handle providers etc..

@NgModule({})
export class APIModule {
  static forRoot(config?: Configuration) {
    // if (config)
    //   will use it latter to inject diff providers 

    let mod = {
      ngModule: APIModule,
      imports: [

      ],
      providers: [
        { provide: 'StorageInterface', useClass: IonicStorage },
        StorageService,
        AuthService,
      ]
    };


    return mod;
  }
}

and I made StorageService to play as the middle man / proxy :

@Injectable()
export class StorageService implements StorageInterface {
    constructor( @Inject(forwardRef(() => 'StorageInterface')) private storage: StorageInterface) {

    }

    Storage() {
        return this.storage;
    }

    SwitchStorage(isLocal: boolean): void {
        this.storage.SwitchStorage(isLocal);
    }

    ClearStorage(): void {
        this.storage.ClearStorage();
    }

    Setter(key: string, value: any): void {
        this.storage.Setter(key, value);
    }

    Getter(key: string) {
        return this.storage.Getter(key);
    }


}

so I can inject StorageService to any page/component etc , and it automatically uses the class I set in the module usesClass .

eg:

export class HomePage {
constructor(public navCtrl: NavController, public navParams: NavParams, private http: Http, private storage: StorageService) {
//storage should be IonicStorage
} 
}

but it errors out :

Uncaught (in promise): Error: No provider for Storage! Error: No provider for Storage! at injectionError (http://localhost:8100/build/vendor.js:1590:86) at noProviderError 

where I have added IonicStorageModule to the main NgModule , what is missing here?

0 Answers
Related