我想要实现的是有条件地添加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
,这里缺少什么?