Angular 2 从模块导出服务

Angular 2 Export Service from Module

我的目录结构是这样设置的:

 app 
  |- core
  |   |_identity
  |   |    |_identity.service.ts
  |   |_ http
  |        |_apiClient.service.ts (service for interacting with my api)
  |-user
  |   |- models
  |   |    |-user.ts
  |   |- services
  |   |     | - user.service.ts
  |   |-listComponent
  |
  |-tenant
      |-models
      |   |-tenant.ts
      |- services
           |- tenant.service.ts
      ....

我的 tenant.service 和 user.service 都注入了​​我的 ApiClient 对象(扩展了 http 服务)。问题是,要引用它,我必须添加

import {ApiClient} from '../../../core/http/apiClient.service'

在我所有想要注入它的组件中。我有一个 core.module 定义(并导入到我的 app.module 中)并且希望能够引用我的 ApiClient 而不必知道目录结构(即我希望能够像import {ApiClient} from '@core/http' 的 http 服务。

这就是模块解析在 Typescript 中的工作方式。

TypeScript will mimic the Node.js run-time resolution strategy in order to locate definition files for modules at compile-time

了解更多信息 here

您可以为您的常用功能创建一个 Angular 库并使用 package.json 安装它,这样通用模块就像其他库一样位于 node_modules 文件夹中。那么您可以在不知道目录路径的情况下轻松使用所有导出的类型,

 import { ApiClient } from 'MyLib';

希望对您有所帮助!!