简体   繁体   中英

Exporting a service from an NgModule with forRoot

I have created a module @foo/bar

static forRoot() : ModuleWithProviders { return { ngModule: BarModule, providers: [BarService] }

I can import from my AppModule

import { BarModule } from '@foo/bar' ... imports: [BarModule.forRoot()}

However, how do I actually use the BarService in a component? Simply importing like this does not get me access to BarService, as I hoped:

import { BarService } from '@foo/bar' // Compile error: there is no BarService

BarService is not same as BarModule , it should have a different location to be imported from.

If you are using VSCode you can just import it using the IDE. check the path from where you import is right!

then consume it inside the constructor as follows,

export class YourComponent{
  constuctor(privatr bar:BarService){
    console.log(this.bar);
}

If you want to use the service you need to inject it

export class MyComponenr {
  constuctor(privatr bar:BarService){
    console.log(bar.someprop);
  }
}

For this to work, you also need the import you already have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM