Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Background:

  • Angular CLI 6 introduced the concept of workspaces.
  • A workspace can contain multiple projects.
  • The workspace and projects' configuration are in an 'angular.json' file in the workspace root folder.
  • Each project can be either an application or a library.
  • The CLI can generate a project that is a library with a command like this:
         ng generate library forms-lib 
  • This command creates a project of type 'library' with a component and service and exports the component.

Question:

I am trying, without success, to create a library and make the services in it available for use in applications which need them.

This code does not work:

import { NgModule } from '@angular/core';
import { FormsLibComponent } from './forms-lib.component'; 
import { FormsLibService } from './forms-lib.service';

@NgModule({
    imports: [],
    declarations: [FormsLibComponent],
    exports: [FormsLibComponent, FormsLibService],
})
export class FormsLibModule {
}

Returns error:

Uncaught Error: Can't export value FormsLibService from FormsLibModule
as it was neither declared nor imported!

Can someone point me in the right direction?

Thank you.

like image 747
Bruce Wilcox Avatar asked May 25 '18 17:05

Bruce Wilcox


People also ask

Which command can be used to create a new library project in an Angular 6 workspace?

The Purpose of Angular Libraries To create a library, we generate it by “ng generate” command, built it by “ng build” command, publish by “npm publish” command. To use a library we install it by “ng i “ command.

Can we export service in Angular?

In your module, you may have your service listed in exports. It should be in your providers; not in imports, declarations, or exports.


2 Answers

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';
like image 111
shahidfoy Avatar answered Sep 29 '22 01:09

shahidfoy


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]
        };
      }
}
like image 31
R. Richards Avatar answered Sep 28 '22 23:09

R. Richards