简体   繁体   English

模块的Angular 2导出服务

[英]Angular 2 Export Service from Module

I have a directory structure set up like this: 我有一个像这样设置的目录结构:

 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
      ....

Both my tenant.service and my user.service inject my ApiClient object (that extends the http service). 我的tenant.service和user.service都注入了我的ApiClient对象(扩展了http服务)。 The problem is, to reference it, I have to add 问题是,要引用它,我必须添加

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

in all of my components that want to inject it. 在我想要注入的所有组件中 I have a core.module defined (and imported into my app.module) and would like to be able to reference my ApiClient without having to know the directory structure (ie I would like to be able to import it like the http service with import {ApiClient} from '@core/http' . 我定义了一个core.module(并将其导入到我的app.module中),并且希望能够引用我的ApiClient而不必知道目录结构(即,我希望能够像使用import {ApiClient} from '@core/http'的http服务一样将其import {ApiClient} from '@core/http'

That is how Module resolution works in Typescript. 这就是在Typescript中模块解析的工作方式。

TypeScript will mimic the Node.js run-time resolution strategy in order to locate definition files for modules at compile-time TypeScript将模仿Node.js运行时解析策略,以便在编译时找到模块的定义文件

Read more about it here . 在此处了解更多信息。

You may create a Angular library for your common functionality and install it using package.json so that the common module is inside node_modules folder like other libraries. 您可以为您的常用功能创建一个Angular库,并使用package.json安装它,以便该通用模块像其他库一样位于node_modules文件夹中。 then you may use all the exported types easily without knowing directory paths like, 那么您可以轻松使用所有导出的类型,而无需了解目录路径,例如,

 import { ApiClient } from 'MyLib';

Hope this helps!! 希望这可以帮助!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM