简体   繁体   中英

Angular2.3 Custom Library and dependency injection

I am trying to inject a service from a custom library created with yeoman into my existing ionic2 project. The index.ts of the lib (which will be installed as npm module) :

@NgModule({
    imports: [
        CommonModule
    ],
    declarations: [
        SampleComponent,
        SampleDirective,
    ],
    exports: [
        SampleComponent,
        SampleDirective,
        SamplePipe
    ]
})
export default class SampleModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: SampleModule,
            providers: [SampleService, SettingsSVC]
         };
    }
}

In my ionic2 App I want to inject SettingsSVC and the module.ts. If I add it to the imports-Section of the app.module it says :

Unexpected value 'SettingsSVC' imported by the module 'AppModule'

If not, I get a console error "provider not found".

The type (class regardless of the @Injectable ) itself is recognized and linked and If I add the same class to my Ionic2 App and its providers section in the module it is working with Injection.

Any suggestions on how to make it work?

Try this,

@NgModule({
  imports: [SampleModule.forRoot()],
  declaretions: [],
  providers: []
})
export class YourAppModule {}

When it says unexpected value , normally means what ever you're importing is not successfully imported.

Either :

1- Path of the SettingsSVC is wrong

2- The name of SettingsSVC is wrong

3- The path is correct but SettingsSVC is not exported

So to make sure your import is actually imported SettingsSVC , put a console.log after it and log it out

import {SettingsSVC} from 'the/path/'

console.log('SettingsSVC',SettingsSVC);

If the log says undefined , it's definitely one of the above ( or maybe something similar ).

And by the way , I got a bit confused , did you want to import SettingsSVC as a service and put it into your providers or did you want to import it as a module and put it into imports:[] ?

You can't have both!

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