Angular 6 CLI Workspaces. How to create library that exports services

前端 未结 6 1480
后悔当初
后悔当初 2021-01-01 18:20

Background:

  • Angular CLI 6 introduced the concept of workspaces.
  • A workspace can contain multiple projects.
  • The workspace and projects\' con
相关标签:
6条回答
  • 2021-01-01 18:58

    I know I am late to the party, but for future references: I got mine resolved by:

    1. ng build FormsLibModule
    2. Add the library's module to the target module and component files as follows:

    import { FormsLibModule } from 'forms-lib';

    Note: VS Code shows this import as an error, but doesn't matter because it compiles fine. Don't try to use auto-import for this import because it is not listed there.

    0 讨论(0)
  • 2021-01-01 18:59

    As far as creating library under angular 8 is considered, we need to export service in public_api.ts export * from './lib/components/spinner/spinner.service';

    0 讨论(0)
  • 2021-01-01 19:10

    My problem was: In the import statement, I picked what (Webstorm) autocomplete gave me, which was roughly the equivalent of

    import {FormsLibModule} from 'forms-lib/lib/forms-lib.module';
    

    Instead, I had to use only the library name:

    import {FormsLibModule} from 'forms-lib';
    

    (Note: I have a workspace which contains the library as well as the app that tests it)

    0 讨论(0)
  • 2021-01-01 19:18

    You can add services you want to export from your library by adding some code into public_api.ts.

    First locate projects/nameOfLibProject/src/public_api.ts inside your angular app then add

    export * from './lib/locationOf/your.service';
    
    0 讨论(0)
  • 2021-01-01 19:19

    This might do the trick for you:

    import { NgModule, ModuleWithProviders } from '@angular/core';
    import { FormsLibComponent } from './forms-lib.component'; 
    import { FormsLibService } from './forms-lib.service';
    
    @NgModule({
        declarations: [FormsLibComponent],
        exports: [FormsLibComponent],
    })
    export class FormsLibModule {
        static forRoot(): ModuleWithProviders {
            return {
              ngModule: FormsLibModule,
              providers: [FormsLibService]
            };
          }
    }
    
    0 讨论(0)
  • 2021-01-01 19:21

    Seems like you have missed to add your service in providers array on module.

    @NgModule({
        imports: [],
        providers: [FormsLibService],
        declarations: [FormsLibComponent, FormsLibService],
        exports: [FormsLibComponent, FormsLibService],
    })
    
    0 讨论(0)
提交回复
热议问题