I'm following the style guide in an Angular 5 project, and I am trying to implement the hardest part of the style guide (core/shared modules). So I want my Core Module to provide a singleton service that is used in all my app. The service is just a wrapper for LocalStorage. So, I created the CoreModule, and added the service to the providers array like this:
CoreModule
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);
}
}
After that, I wanted to use the LocalStorageService in a feature module, so I imported it, and injected it in the constructor using the normal DI way.
Unfortunately I get TypeError: this.localStorageService is undefined
What I missed ? Thanks in advance
Well as mentioned in the question's comment, that was a JavaScript context issue not an Angular one, so I changed the inputChange
method to using the ES6 arrow function feature and it worked like charm.