How to create configurable service Angular 4

Viewed 1866

I would like to create a service to be re-used throughout a couple of angular applications.

I'm using angular-cli.

I want the service to be configurable. In other words, give each app the ability to instantiate the service with different config parameters, using DI.

The service will sit in a shared library, so it cannot import a specific file path from the parent application in order to get the config params, it has to get them via DI.

I tried following the instructions here, since the article describes exactly the problem I am facing, however I am getting an error:

ERROR Error: No provider for String!
at injectionError (core.es5.js:1169)
at noProviderError (core.es5.js:1207)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._throwOrNull (core.es5.js:2649)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._getByKeyDefault (core.es5.js:2688)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._getByKey (core.es5.js:2620)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.get (core.es5.js:2489)
at resolveNgModuleDep (core.es5.js:9533)
at _createClass (core.es5.js:9572)
at _createProviderInstance$1 (core.es5.js:9544)
at resolveNgModuleDep (core.es5.js:9529)

Also, from zone.js:

zone.js:643 Unhandled Promise rejection: No provider for String! ; Zone: <root> ; Task: Promise.then ; Value: Error: No provider for String!

Here is my relevent code:

main.ts:

...
import { provideAuthService } from 'shared-library';
...
platformBrowserDynamic().bootstrapModule(AppModule, [provideAuthService('Good Day')]);

app.module.ts:

...
import { AuthService } from 'shared-library';

@NgModule({
  declarations: [
      ...
  ],
  imports: [
    ...
  ],
  providers: [
    AuthService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

and auth.service.ts:

...

export function provideAuthService(settings:string) {  
  return { provide: AuthService, useFactory: () => new AuthService(settings) 
}

@Injectable()
export class AuthService {
mgr: UserManager = new UserManager(this.settings);

    constructor(private settings:string='Hello') {
       ...
    }
}

Thanks in advance to anyone who might be able to help out here!

1 Answers
Related