我正在开发基于Angular 7的Ionic 4应用程序,并希望创建一个作为单例实例提供给整个应用程序的服务。
根据Angular 7文档的最新版本,您无需在app.module.ts的providers部分中指定服务,您可以轻松地使用provideIn来对服务进行注释:'root'注释,然后注入它在组件/页面中。
服务文件:
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor(public storage: Storage) {}
...
}
然后我将其像这样注入到我的组件构造函数中:
import { StorageService } from '../services/storage.service';
@Component({
selector: 'app-add',
templateUrl: './add.page.html',
styleUrls: ['./add.page.scss'],
})
export class AddPage implements OnInit {
constructor(private storage: StorageService) { }
ngOnInit() {}
...
}
但是当我启动我的应用程序时,出现此错误:
Uncaught (in promise): Error: StaticInjectorError(AppModule)[Storage]:
StaticInjectorError(Platform: core)[Storage]:
NullInjectorError: No provider for Storage!
答案 0 :(得分:1)
在主模块中,将IonicStorageModule替换为IonicStorageModule.forRoot()
imports: [
IonicStorageModule.forRoot()
]