lil-works
lil-works

Reputation: 710

how do I inject a service from an angular library to another angular library

I have to angular libraries in the projects folder

ng generate library foo
ng generate library bar

My foo library contain a public_api.ts which wrap the library files

export * from './lib/foo.service';

I have a service in foo define as abstract class

export abstract class FooService {}

I want to extend the fooService in a Bar service

import { FooService } from 'projects/foo/src/public_api';
export class BarService extends FooService{}

I got this error

BUILD ERROR
error TS6059: File '/projects/foo/src/lib/foo.service.ts' is not under 'rootDir' 'projects/bar/src'. 'rootDir' is expected to contain all source files.
error TS6059: File '/projects/foo/src/public_api.ts' is not under 'rootDir' '//projects/bar/src'. 'rootDir' is expected to contain all source files.

How I can get my foo library from bar?

Upvotes: 0

Views: 2528

Answers (1)

Yevhenii Dovhaniuk
Yevhenii Dovhaniuk

Reputation: 1103

Try to treat libraries as a separate projects (even if they are located inside a single source tree).

How to make your approach work: (starting from scratch)

  1. ng new libs-test
  2. ng generate library foo
  3. ng generate library bar
  4. ng build foo
  5. npm i foo@file:dist/foo // this adds a local dependency for your app project to the foo library
  6. Open the package.json of the libary bar and add the "foo": "latest" dependency:

    {
      "name": "bar",
      "version": "0.0.1",
      "peerDependencies": {
        "@angular/common": "^7.2.0",
        "@angular/core": "^7.2.0",
        "foo": "latest" // add this line
      }
    }

  1. Go the the BarService inside the bar library:

    import { Injectable } from '@angular/core';
    import { FooService } from 'foo';

    @Injectable({
      providedIn: 'root'
    })
    export class BarService extends FooService{

      constructor() {
        super();
      }
    }

Please note the non-relative import { FooService } from 'foo';

  1. Build your bar library: ng build bar

That's it! Your bar library correctly uses the foo functionality.

If you want to use the bar's service in your app simply do the following:

  1. ng build bar
  2. npm i bar@file:dist/bar
  3. In your AppComponent:

    import { Component } from '@angular/core';
    import { BarService } from 'bar';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.less']
    })
    export class AppComponent {
      title = 'libs-test';

      constructor(private barService: BarService) {

      }
    }

  1. Make sure your app is building properly: ng build --aot

Upvotes: 3

Related Questions