Angular 5 功能模块中未定义的核心模块服务

Angular 5 Core module service undefined in feature module

我在 Angular 5 项目中遵循风格指南,并且我正在尝试实现风格指南中最难的部分(core/shared 模块)。所以我希望我的核心模块提供一个在我所有应用程序中使用的单例服务。该服务只是 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

我错过了什么?提前致谢

看看这个post。

我想它会解决你的问题。

正如问题评论中提到的那样,这是一个 JavaScript 上下文问题而不是 Angular 问题,所以我将 inputChange 方法更改为使用 ES6 箭头函数功能和效果很好。