【发布时间】:2018-02-05 15:42:23
【问题描述】:
我正在遵循 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.');
}
}
}
MyLazyComponent
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
我错过了什么?提前致谢
【问题讨论】:
-
你能展示你的功能模块代码吗?从您的问题中并不清楚......但您不会将服务注入模块,而是注入组件,对吗?你能也展示一下代码吗?
-
当然,我会更新我的问题以添加源代码。我想在风格指南中指定的核心模块中使用单例服务,这个链接:angular.io/guide/singleton-services
-
@DeborahK 好吧,我明白了,这只是一个 JavaScript 上下文问题,而不是角度单例问题,我只是将 inputChange 方法移动到 ES6 箭头函数样式,它就像魅力一样工作。与此同时,Deborah Kurata 夫人对我的帮助让我感到非常荣幸。非常感谢!
标签: angular singleton angular2-styleguide