Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Use service from other module

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?

like image 547
Jeanluca Scaljeri Avatar asked Mar 26 '26 17:03

Jeanluca Scaljeri


1 Answers

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) {
        ...
    }
}
like image 186
Darshita Avatar answered Mar 28 '26 07:03

Darshita