Angular 6+ providedIn: 'root' raising a StaticInjectorError

Viewed 270

I have googled extensively and I can't seem to find anyone else with this issue, so I must be missing something. I am converting all of my AppModule services to use the providedIn: 'root' method, but it doesn't seem to be working.

import { Injectable } from '@angular/core';

Injectable({
    providedIn: 'root'
})
export class CommonService{
    UserName : string = 'Guest';
    Roles : Array<any> = [];
    Theme: string = 'standard';

    constructor(){}
}

Here is one of the components that uses the service:

import { CommonService } from './Services/common.service';

@Component({
    selector: 'navBar',
  templateUrl: './navbar.html'
})

export class NavBar {

    constructor(private session: CommonService) {}

At runtime, this is the error in the console:

StaticInjectorError(AppModule)[NavBar -> CommonService]: StaticInjectorError(Platform: core)[NavBar -> CommonService]: NullInjectorError: No provider for CommonService!

I've checked the documentation, and I don't see where I am going wrong. What am I missing?

Forgot to mention, NavBar is a component declared in SharedModule, SharedModule is imported in AppModule.

1 Answers

You may be missing the leading "@" on Injectable:

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class CommonService{
    UserName : string = 'Guest';
    Roles : Array<any> = [];
    Theme: string = 'standard';

    constructor(){}
}

There may not be an error in the IDE, but that looks like it might be the issue

Related