Ionic有条件地添加服务提供商

时间:2017-09-27 08:22:45

标签: angular ionic-framework dependency-injection ionic3

我想要实现的是有条件地添加providers,如下所示:

制作了interface

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

然后将class改为implement

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) {

    }
}

然后module来处理提供者等。

@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;
  }
}

我将StorageService作为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);
    }


}

所以我可以将StorageService注入任何page/component等,它会自动使用我在模块usesClass中设置的类。

例如:

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

但它出错:

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 

我已将IonicStorageModule添加到主NgModule,这里缺少什么?

0 个答案:

没有答案