3

I'm trying to import a service from outside a module.

The setup I have is as follows: I have this Foo module

@NgModule({
    declarations: [
        FooComponent
    ],
    exports: [
        FooComponent
    ],
    providers:[
        FooService
    ]
});
export class FooModule {}

which I import in app.module.ts

@NgModule({
    ...
    imports: [ FooModule ]
});
...

This works fine.

Next I want to import FooService from within app.module.ts, so I moved the line providers: { FooService } to app.module.ts

@NgModule({
    ...
    providers: [FooService],
    imports: [ FooModule ]
});
...

So far the app still works. The final step, I copied the service file outside the foo directory, I changed the import path, I even restarted the server and now I get an error in the browser

EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: No provider for FooService!

It cannot find the service anymore.

Any suggestions why the service is missing when the service file is not in the foo directory ? And can this be fixed somehow?

1 Answer 1

4

I have tried following solution. It's working for me :

Foo Module

@NgModule({
    declarations: [
        FooComponent
    ],
    exports: [
        FooComponent
    ],
});
export class FooModule {}

app.module.ts

import {Fooservice} from './FooService';
@NgModule({
    ...
    imports: [ FooModule ]
    providers: [FooService],
});
...

Foo.component.ts

import { Component } from '@angular/core';
import { FooService }       from '../FooService'; 

@Component({

})
export class FooComponent {

    constructor(public fooservice: FooService) {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You're correct, this does work, thanks, It turned out I forgot to remove an import in an other file after I refactored :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.