我正在遵循 Angular 5 项目中的样式指南,并且正在尝试实现样式指南中最难的部分(核心/共享模块)。所以我希望我的核心模块提供一个在我的所有应用程序中使用的单例服务。该服务只是 LocalStorage 的包装器。因此,我创建了 CoreModule,并将服务添加到 providers 数组中,如下所示:
核心模块
import { NgModule, Optional, SkipSelf } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LocalStorageService } from './local-storage.service';
@NgModule({
imports: [
CommonModule,
],
exports: [
CommonModule,
],
providers: [ LocalStorageService ],
declarations: [ ]
})
export class CoreModule {
constructor( @Optional() @SkipSelf() parentModule: CoreModule) {
if (parentModule) {
throw new Error('CoreModule has already been loaded. You should only import Core modules in the AppModule only.');
}
}
}
我的懒惰组件
import { Component, OnInit, Input, Output, ViewChild } from '@angular/core';
import { LocalStorageService } from '@app/core/local-storage.service';
@Component({
selector: 'app-my-lazy',
templateUrl: './my-lazy.component.html',
styleUrls: ['./my-lazy.component.scss']
})
export class MyLazyComponent implements OnInit {
constructor(private localStorageService: LocalStorageService) { }
ngOnInit() {
this.debounceValues();
}
inputChange(data) {
this.localStorageService.setItem('saveData', data);
}
debounceValues() {
this.form.valueChanges
.debounceTime(1000)
.distinctUntilChanged()
.subscribe(this.inputChange);
}
}
之后,我想在一个特性模块中使用 LocalStorageService,所以我导入了它,并使用普通的 DI 方式将它注入到构造函数中。不幸的是我得到TypeError: this.localStorageService is undefined
我错过了什么?提前致谢