首页 文章

NullInjectorError:Angular 2中没有InjectionToken LOCAL_STORAGE的提供者

提问于
浏览
0

在我的项目中,我正在使用' angular-webstorage-service '中的LOCAL_STORAGE模块 . 它的功能很好,但我在测试时遇到错误 . 我正在使用Kharma和Jasmine

我没有得到我做错的地方,如果有人碰到这个,请告诉我 .

失败:StaticInjectorError(DynamicTestModule)[AppComponent - > InjectionToken LOCAL_STORAGE]:StaticInjectorError(Platform:core)[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

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

    import { StorageServiceModule } from 'angular-webstorage-service';
    
    imports: [StorageServiceModule ]
    

相关问题