Angular 7 单例服务:没有服务提供者
Angular 7 Singleton Service: No provider for Service
我正在开发一个基于 Angular 7 的 Ionic 4 应用程序,我想创建一个服务,作为一个单例实例提供给整个应用程序。
根据 Angular 7 的最新版本文档,您无需在 app.module.ts 的提供程序部分指定服务,您可以轻松地使用 providedIn 注释服务:'root' 注释,然后将其注入 components/pages。
服务文件:
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!
在主模块中,将 IonicStorageModule 替换为 IonicStorageModule.forRoot()
imports: [
IonicStorageModule.forRoot()
]
我正在开发一个基于 Angular 7 的 Ionic 4 应用程序,我想创建一个服务,作为一个单例实例提供给整个应用程序。
根据 Angular 7 的最新版本文档,您无需在 app.module.ts 的提供程序部分指定服务,您可以轻松地使用 providedIn 注释服务:'root' 注释,然后将其注入 components/pages。
服务文件:
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!
在主模块中,将 IonicStorageModule 替换为 IonicStorageModule.forRoot()
imports: [
IonicStorageModule.forRoot()
]