如何从一个角度库向另一个角度库注入服务

时间:2018-10-31 13:59:57

标签: angular

我必须在项目文件夹中添加角度库

ng generate library foo
ng generate library bar

我的foo库包含一个包装库文件的public_api.ts

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

我在foo中有一个服务定义为抽象类

export abstract class FooService {}

我想在Bar服务中扩展fooService

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

我收到此错误

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.

如何从bar获取我的foo库?

1 个答案:

答案 0 :(得分:0)

尝试将库视为单独的项目(即使它们位于单个源树中)。

如何使您的方法有效:(从头开始)

  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 //这会将您的应用程序项目的本地依赖项添加到foo库
  6. 打开库bar的package.json并添加"foo": "latest"依赖项:

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

  1. 进入BarService库中的bar

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

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

      constructor() {
        super();
      }
    }

请注意非亲戚import { FooService } from 'foo';

  1. 构建您的bar库:ng build bar

就是这样!您的bar库正确使用了foo功能。

如果您想在应用程序中使用bar的服务,只需执行以下操作:

  1. ng build bar
  2. npm i bar@file:dist/bar
  3. 在您的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. 确保您的应用正常构建:ng build --aot