NullInjectorError:在Angular 2中没有为InjectionToken LOCAL_STORAGE提供程序

时间:2018-09-14 02:11:30

标签: angular

在我的项目中,我正在使用“ angular-webstorage-service ”中的LOCAL_STORAGE模块。 它的功能正常,但是在执行测试时出现错误。我正在使用Kharma和茉莉花

我没有弄错我在哪里,请让我知道是否有人遇到这个问题。

  

失败:StaticInjectorError(DynamicTestModule)[AppComponent-> InjectionToken LOCAL_STORAGE]:     StaticInjectorError(平台:核心)[AppComponent-> InjectionToken LOCAL_STORAGE]:       NullInjectorError:没有InjectionToken LOCAL_STORAGE的提供程序!

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { StorageServiceModule} from 'angular-webstorage-service';
//import * as $ from 'jquery';
import * as bootstrap from "bootstrap";


import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent    
  ],
  imports: [
    BrowserModule,
    StorageServiceModule
  ],
  schemas: [ NO_ERRORS_SCHEMA],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component, OnInit, HostListener, Inject } from '@angular/core';

import {LOCAL_STORAGE, WebStorageService, StorageServiceModule} from 'angular-webstorage-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {

constructor(@Inject(LOCAL_STORAGE) private storage: WebStorageService) {
}

}

karma.conf.js

// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    files: [ 
      { pattern: '../node_modules/jquery/dist/jquery.min.js', watched: false }
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

1 个答案:

答案 0 :(得分:-1)

只需将“ StorageServiceModule”导入到app.module中 该StorageServiceModule为Web Storage API提供服务包装。每当您的应用程序需要使用localStorage或sessionStorage

import { StorageServiceModule } from 'angular-webstorage-service';

imports: [StorageServiceModule ]