angular: Angular 5.0.0 error: StaticInjectorError[InjectionToken DocumentToken]

I’m submitting a…


[x] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

I have upgraded my current project from 4.4.4 to 5.0.0 using the recommandations from https://angular-update-guide.firebaseapp.com/

And now when I launch ng serve, the page keeps blank and the browser console returns the following error:

zone.js:391 Uncaught (in promise) Error: StaticInjectorError[InjectionToken DocumentToken]: 
  StaticInjectorError[InjectionToken DocumentToken]: 
    NullInjectorError: No provider for InjectionToken DocumentToken!

The traceback indicates it comes from the bootstraping in my main.ts:

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

but unfortunately, nothing more specific.

Expected behavior

No error.

Minimal reproduction of the problem with instructions

I do not know how to reproduce this bug, my existing codebase is quite large.

I am aware it might be difficult to answer my issue, but I just ask to know if this error message rings a bell to anyone, so I know where to start digging.

What is the motivation / use case for changing the behavior?

Environment

Angular CLI: 1.5.0
Node: 8.7.0
OS: darwin x64
Angular: 5.0.0
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cdk: 2.0.0-beta.8
@angular/cli: 1.5.0
@angular/flex-layout: 2.0.0-beta.9
@angular/material: 2.0.0-beta.8
@angular-devkit/build-optimizer: 0.0.32
@angular-devkit/core: 0.0.20
@angular-devkit/schematics: 0.0.35
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.0
@schematics/angular: 0.1.0
typescript: 2.4.2
webpack-bundle-analyzer: 2.9.0
webpack: 3.8.1

Browser:

  • Chrome (desktop) version XX
  • Chrome (Android) version XX
  • Chrome (iOS) version 62.0.3202.62
  • Firefox version XX
  • Safari (desktop) version XX
  • Safari (iOS) version XX
  • IE version XX
  • Edge version XX

For Tooling issues:

  • Node version: XX <!-- run node --version -->
  • Platform:

Others:

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 14
  • Comments: 55 (3 by maintainers)

Commits related to this issue

Most upvoted comments

No need to import HttpModule import {HttpModule} from ‘@angular/http – Not Required

Just make sure, you have provided your service in providers after importing it in app.module.ts Like -

import { ApiService } from ‘./app.service’ imports: [ BrowserModule, ], providers: [ApiService],

I think this error occurs because you need to import HttpModule(deprecated) as well as HttpClientModule, because some dependency still relies on HttpModule.

import {HttpClientModule, HttpClient} from ‘@angular/common/http’;

then: imports:[ HttpClientModule]

will be ok

Add this in app.module.ts

import { HttpClientModule } from ‘@angular/common/http’

and also add HttpClientModule in your imports

@Sagar1990 have you imported this

import { HttpClientModule } from ‘@angular/common/http’

in app.module.ts?

Yes adding these below to app.module.ts worked. Thanks @usmanakram1996

import { HttpModule } from ‘@angular/http’;

and importing worked

imports: [ HttpModule ]

@ochezeau You’ll need --preserve-symlinks in (app’s) build when (lib) link to a different repo. That’s what happened in #20102.

Same error, but only works on some components and routes, any solution?

captura de tela de 2017-11-08 14-13-59

Stuck here The xxxx xxxxx this xxx … Help out guys with exact matching solution all solutions are xxxxx… NEED PROPER HELP ERROR Error: StaticInjectorError(AppModule)[AppComponent -> AngularFireDatabase]: StaticInjectorError(Platform: core)[AppComponent -> AngularFireDatabase]: NullInjectorError: No provider for AngularFireDatabase! at NullInjector.get (core.js:1002) at resolveToken (core.js:1300) at tryResolveToken (core.js:1242) at StaticInjector.get (core.js:1110) at resolveToken (core.js:1300) at tryResolveToken (core.js:1242) at StaticInjector.get (core.js:1110) at resolveNgModuleDep (core.js:10854) at NgModuleRef.get (core.js:12087) at resolveDep (core.js:12577)

Please reply or comment Only If You Know where this makes shit…

I solve this by following two steps:

import { BrowserModule } from ‘@angular/platform-browser’; … imports: [ BrowserModule, ]

Not working with any of the solutions above

Attached are the files— appmodulets homets packagejson

I fixed my problem. For me, everything was working well with a : build --prod I had the problem using a common library (unsing an npm link) and with the command ng build --watch (I use a tomcat server) I fixed the problem using the command: npm build --aot --watch (adding --aot) Is is alos important to have the right version of components : angular-cli : 1.5 and typescript 2.4.2

I got this error after importing a component library I built with ng-packagr. I had to change the dependencies parameter to peerDependencies in the package.json of my component library as outlined here. This cost me days to root out.

I am getting the same error, including Httpmodule did not work for me.

my app.module.ts: -


import { NgModule, Injectable } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { HttpModule } from '@angular/http';


import { ModalModule } from 'ngx-modialog';
import { BootstrapModalModule, Modal, bootstrap4Mode } from 'ngx-modialog/plugins/bootstrap';

import { AppComponent } from './app.component';
import { ExportToPdfComponent } from './exportTopdf/exportTopdf.component';
import { InvalidPageComponent } from './invalidPage/invalidPage.component';

import { ViewCountService } from './Service/viewsCount.component';

const appRoutes: Routes = [
    { path: 'home', component: AppComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'export', component: ExportToPdfComponent },
    { path: '**', component: InvalidPageComponent }
];

@NgModule({
    imports: [
        BrowserModule,
        HttpModule,
        RouterModule.forRoot(appRoutes),
        ModalModule.forRoot(),
        BootstrapModalModule
    ],
    declarations: [
        AppComponent,
        ExportToPdfComponent,
        InvalidPageComponent
    ],
    bootstrap: [
        AppComponent
    ],
    providers: [
        ViewCountService
    ]
})



export class AppModule { }

exportTopdf.component.ts file: -

import { Component, ViewContainerRef, ViewEncapsulation } from '@angular/core';
import { ViewCountService } from '../Service/ViewsCount.component';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

@Component({
    selector: 'export-to-pdf',
    templateUrl: 'app/exportTopdf/exportTopdf.component.html',
})
export class ExportToPdfComponent {
    name: string;
    fields: any;

    constructor(public modal: Modal, private ViewCountService: ViewCountService) {
        debugger;
        this.fields = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
    }


    getViewCount(): void {
        debugger;
        this.ViewCountService.getViewCount()
            .then(data => {
                this.name = data;
                console.log("I CANT SEE DATA HERE: ", this.name)
            });
    }

}

my service code: -


import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ViewCountService {
    constructor(private http: Http) {
    }

    getViewCount() {
        return this.http.get('api/Tableau/GetViewsCount')
            .map(response => response.json() as string).toPromise();
    }

    getDataObservable(url: string) {
        return this.http.get('api/Tableau/GetViewsCount')
            .map(data => {
                data.json();
                console.log("I CAN SEE DATA HERE: ", data.json());
            });
    }

}

system.config.js: -


/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        transpiler: 'typescript',
        //typescript compiler options
        typescriptOptions: {
            emitDecoratorMetadata: true
        },
        paths: {
            // paths serve as alias
            'npm:': '/node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            'app': 'app',

            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

            // other libraries
            'rxjs': 'npm:rxjs',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',

            'ngx-modialog': 'npm:ngx-modialog/bundle/ngx-modialog.umd.min.js',
            'ngx-modialog/plugins/bootstrap': 'npm:ngx-modialog/plugins/bootstrap/bundle/ngx-modialog-bootstrap.umd.min.js'


        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                defaultExtension: 'js',
                meta: {
                    './*.js': {
                        loader: 'systemjs-angular-loader.js'
                    }
                }
            },
            rxjs: {
                defaultExtension: 'js'
            }
        }
    });
})(this);

package.json: -

{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "build:e2e": "tsc -p e2e/",
    "serve": "lite-server -c=bs-config.json",
    "serve:e2e": "lite-server -c=bs-config.e2e.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "pree2e": "npm run build:e2e",
    "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
    "preprotractor": "webdriver-manager update",
    "protractor": "protractor protractor.config.js",
    "pretest": "npm run build",
    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
    "pretest:once": "npm run build",
    "test:once": "karma start karma.conf.js --single-run",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~5.0.3",
    "@angular/compiler": "~5.0.3",
    "@angular/core": "~5.0.3",
    "@angular/forms": "~5.0.3",
    "@angular/http": "~5.0.3",
    "@angular/platform-browser": "~5.0.3",
    "@angular/platform-browser-dynamic": "~5.0.3",
    "@angular/router": "~5.0.3",
    "angular-in-memory-web-api": "~0.5.1",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "ngx-modialog": "^5.0.0",
    "rxjs": "5.5.2",
    "systemjs": "0.20.19",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "concurrently": "^3.2.0",
    "lite-server": "^2.2.2",
    "typescript": "~2.6.1",
    "canonical-path": "0.0.2",
    "tslint": "^5.8.0",
    "lodash": "^4.16.4",
    "jasmine-core": "~2.8.0",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.2.0",
    "rimraf": "^2.5.4",
    "@types/node": "^8.0.53",
    "@types/jasmine": "2.8.2"
  },
  "repository": {}
}

Error i am getting is: -


ERROR Error: Uncaught (in promise): Error: StaticInjectorError[ViewCountService]: 
  StaticInjectorError[ViewCountService]: 
    NullInjectorError: No provider for ViewCountService!
Error: StaticInjectorError[ViewCountService]: 
  StaticInjectorError[ViewCountService]: 
    NullInjectorError: No provider for ViewCountService!
    at _NullInjector.get (injector.js:31)
    at resolveToken (injector.js:387)
    at tryResolveToken (injector.js:330)
    at StaticInjector.get (injector.js:170)
    at resolveToken (injector.js:387)
    at tryResolveToken (injector.js:330)
    at StaticInjector.get (injector.js:170)
    at resolveNgModuleDep (ng_module.js:103)
    at NgModuleRef_.get (refs.js:1037)
    at resolveDep (provider.js:455)
    at _NullInjector.get (injector.js:31)
    at resolveToken (injector.js:387)
    at tryResolveToken (injector.js:330)
    at StaticInjector.get (injector.js:170)
    at resolveToken (injector.js:387)
    at tryResolveToken (injector.js:330)
    at StaticInjector.get (injector.js:170)
    at resolveNgModuleDep (ng_module.js:103)
    at NgModuleRef_.get (refs.js:1037)
    at resolveDep (provider.js:455)
    at resolvePromise (zone.js:824)
    at resolvePromise (zone.js:795)
    at zone.js:873
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (ng_zone.js:575)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at ZoneTask.invokeTask [as invoke] (zone.js:503)
    at invokeTask (zone.js:1540)
defaultErrorLogger @ errors.js:48
ErrorHandler.handleError @ error_handler.js:90
next @ application_ref.js:311
schedulerFn @ event_emitter.js:156
SafeSubscriber.__tryOrUnsub @ Subscriber.ts:254
SafeSubscriber.next @ Subscriber.ts:204
Subscriber._next @ Subscriber.ts:135
Subscriber.next @ Subscriber.ts:95
Subject.next @ Subject.ts:61
EventEmitter.emit @ event_emitter.js:131
(anonymous) @ ng_zone.js:605
ZoneDelegate.invoke @ zone.js:392
Zone.run @ zone.js:142
NgZone.runOutsideAngular @ ng_zone.js:404
onHandleError @ ng_zone.js:605
ZoneDelegate.handleError @ zone.js:396
Zone.runGuarded @ zone.js:158
_loop_1 @ zone.js:702
api.microtaskDrainDone @ zone.js:711
drainMicroTaskQueue @ zone.js:610
ZoneTask.invokeTask @ zone.js:503
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566

Is this a troll post XD Go SO wtf

All you need to do is to import your service in your app.module, like,

import { HeroService } from ‘…/app/hero.service’;

and then, provide it to your providers array in the same file, like,

providers: [HeroService]

I hope this will help…

Hey, I’m struggling with similar issue as this stackOverFlow question - Angular can’t use HttpClient in external library. In short - i’m trying to compile my app as a ng-module (using ngc), so it could be imported by another outer app. Unfortunately, though my app works fine by itself; it can’t be imported by the outer app, due to the error mentioned above. None of the solutions suggested above solved the problem. Help would be appreciated.

In my case, a Route guard was not added to the providers: any[] inside of @ngModule;

@NgModule({
  declarations: [
    BookingFormComponent,
    AppComponent,
    HomeComponent,
    BookingNotFoundComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    ReactiveFormsModule
  ],
  providers: [BookingFormGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

I was like, HAY HOERAY let’s start a new project (templated from Visual Studio 2017 v15.7.3) didn’t even run out of the box but I want to upgrade angular anyway to 6, did that, solved every dependency issue that was raised until no warnings were left. Boom, got this, no issue seems to resolve my issue. Ended up copy-pasting an other web project with angular 5.0.1 which works.

Angular Team, I call this unstable release management.

I already had these import statements inside my app.module.But still the StaticInjectorError …NullInjectorError poped up.

import { BrowserModule } from ‘@angular/platform-browser’; import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’; import { HttpClientModule } from ‘@angular/common/http’;

THIS IS HOW I GOT IT RESOLVED The error happened because I forgot to import my service into app.module.ts file.

import {xyzNotificationService } from './services/eventoccurrences.service';

and then add your service for eg., xyzNotificationService__ to the providers: [ ] section of your app.module

I have the same problem with Angular 5.2.7 When i try to add :

 import {ActivatedRoute} from "@angular/router";

 constructor(private router: ActivatedRoute) {}

In my component, this generates an error :

AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: StaticInjectorError(AppModule)[AppComponent -> ActivatedRoute]: StaticInjectorError(Platform: core)[AppComponent -> ActivatedRoute]: NullInjectorError: No provider for ActivatedRoute!

I have try all solution exposed in above but no works…

@kverma17 You only need to change your dependencies to peerDependencies if you are building a library. You might try updating all angular dependencies to latest, I know better error definitions for this error were a part of 5.2 or 5.1. I am guessing some library you are dependent on changed their syntax without documenting it as happened to en-sevilla. Firebase hase been bad about making these kinds of changes lately, I see you importing firebase in your app module but I don’t see it in your package.json. If you are using "firebase": "4.8.1" roll it back to 4.8.0 as they made breaking changes to the way the modules are imported in 4.8.1.