NullInjectorError:没有提供者为InjectionToken DocumentToken

时间:2018-01-22 11:07:30

标签: angular

我为所有Angular 5项目设置了一个公共库。 Library是GitHub存储库angular-library-starter-kit的克隆。

在尝试使用HttpClientModuleHttpModule的后继者)之前,一切正常。

以下是我的library.module.ts文件的内容:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
import { MyService } from './my-service';

export * from './my-service';

@NgModule({
  imports: [
    CommonModule,
    HttpModule,
    HttpClientModule
  ],
  exports: [
  ],
  declarations: [
  ],
  providers: [
      MyService
  ],
})
export class LibraryModule { }

以下是my-service.ts的内容(图书馆中 THE ONLY FILE ):

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Observable";

@Injectable()
export class MyService {

    constructor(private httpClient: HttpClient) {
        //
    }

    getData(): Observable<any> {
        return this.httpClient.get<any>('test.json');
    }

}

库构建时没有任何错误,但是当我尝试在新的Angular 5应用程序(ng new myApp)中使用它时,它会出错:

AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: StaticInjectorError(AppModule)[HttpXsrfTokenExtractor -> InjectionToken DocumentToken]: 
  StaticInjectorError(Platform: core)[HttpXsrfTokenExtractor -> InjectionToken DocumentToken]: 
    NullInjectorError: No provider for InjectionToken DocumentToken!
    at _NullInjector.get (core.js:994)
    at resolveToken (core.js:1292)
    at tryResolveToken (core.js:1234)
    at StaticInjector.get (core.js:1102)
    at resolveToken (core.js:1292)
    at tryResolveToken (core.js:1234)
    at StaticInjector.get (core.js:1102)
    at resolveNgModuleDep (core.js:10847)
    at _createClass (core.js:10888)
    at _createProviderInstance$1 (core.js:10858)

我甚至尝试在Angular 5应用中导入模块HttpModuleHttpClientModule,但我遇到了同样的错误。

我也尝试从应用和库中删除HttpModule,但仍然是同样的错误。

我同时使用HttpModuleHttpClientModule的原因是apparently HttpClientModule依赖HttpModule工作。 我了解到这不是真的。

我该如何解决这个问题?

注意:ng serve添加LibraryModule之前,全新的应用与imports的工作正常。

2 个答案:

答案 0 :(得分:2)

我读不及GitHub Issue。显然,在使用本地库时,您必须将--preserve-symlinks参数添加到ng serve

ng serve --preserve-symlinks

此外,无需在任何地方导入HttpModule,如果只有库依赖它,则无需在应用内导入HttpClientModule

答案 1 :(得分:1)

更新为 Eric的答案:

自从删除Angular / Cli v6 --preserve-symlinks参数以来。要添加它,请相应地编辑angular.json文件:

[...]  
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "progress": true,
        "extractCss": false,
        "outputPath": "dist/xcs-web-ui",
        "index": "src/index.html",
        "main": "src/main.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "src/tsconfig.app.json",
        "preserveSymlinks": true,
[...]