Search code examples
angularangular2-injection

`ng serve` fails if service is not provided directly in component


I have a project structured like so:

project
-src
--app
---project
----project.component.ts
----project.component.html
----project.component.sass
---project.module.ts
---project.service.ts

From within my component I am attempting to use the service:

constructor(private ProjectService: ProjectService) {
    this.ProjectService = ProjectService;
}

But when I run ng serve it fails saying ERROR in /Users/jrquick/uabshp/project/src/app/project/project.component.ts (9,49): Cannot find name 'ProjectService'

Even though I have the service in the project.module.ts file:

import { ProjectService } from './project.service';

@NgModule({
    declarations: [
        ProjectComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule
    ],
    providers: [
        ProjectService
    ],
    bootstrap: [
        ProjectComponent
    ],
    exports: [
        ProjectComponent,
        ProjectService
    ]
})

I have tried adding it to my component annotation's providers array but I'd prefer the service is used a singleton. I can also directly import the service in the project.compontent.ts file (like below) but it is not ideal to have to have the same import statement copy and pasted within the module as well as multiples components and services.

import { ProjectService } from './project.service';

project.service.ts declaration:

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

@Injectable()
export class DefaultVariableService {
    constructor() {

    }

   ...
}

Solution

  • Try this, because you trying import ProjectService from the same folder in which ProjectComponent is located. Your import of ProjectService in project.component.ts should look like

    import { ProjectService } from '../project.service';
    

    Secondly, why do you use strange stuff like:

    constructor(private ProjectService: ProjectService) {
        this.ProjectService = ProjectService;
    }
    

    What is the purpose of this?! I think that it should look like:

    constructor(private projectService: ProjectService) {
    
    }
    

    and that's all! You can use this service in your component in this way:

    this.projectService.someMethod()