Angular - Services are not exported from a custom library to consumer project

Viewed 737

I build an angular library, that has two types of services (along with components/modules)

  • Services private to the library, used for internal functionality that should not be available to the consumer project (let's call them internal)

  • Services that should be used to move data between the library's components/modules and the consumer project.(let's call them external)

Both cases are a bit problematic and thus they get one section each. Sorry for the long post.


Note Every library component is also a module, in order to selectively import what is needed, and not the whole library


Internal Services

They are packed with the module using the forRoot() method as shown bellow:

export class TestModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: TestModule,
      providers: [ TestService ]
    }
  }
} 

and then in the consumer projects app.module

TestModule.forRoot() is used.

Everything here works fine. The weird thing is when I use the selector of the component packed in the TestModule as a view child I can access externally a private property. Here are some snippets to make it clearer what happens:

<test-selector #testViewChild></test-selector>

@ViewChild('testViewChild') testViewChild;

this.testViewChild.testService.myTestValue = 'I was set in the test project'

The last snippet is from the typescript file of the TestComponent in the exported in the TestModule

 constructor(private testService: TestService) {
    this.testService.myTestValue = 'I was set in the library';
  }

The actual service myTestValue === 'I was set in the test project'

Anyone knows why this happens?!


External Services

Here things are weirder. As the library was first created it was bundled with gulp, but later it was switched to webpack. If I have everything straight in my mind, with gulp the services defined in the library had to be provided through the app.module of the consumer project and then there was this global service instance used both by the library and consumer project components.

After the switch to webpack, these services fail to be instantiated, throwing an error about the services having no providers, and although exported (in the index.ts) they can not be imported from the consumer app.module using from 'test-library'. A workaround was to set the path like from '../../node_modules/test-library/......'. But this just runs into more problems.

By using providers inside the library the service instances cannot be accessed from the consumer project (except with the hack above that feels utterly wrong).

So any ideas on what is going on? Once again sorry for the long post. And for a better and more descriptive title feel free to edit.

0 Answers
Related