如何找到根 Angular 目录?

How can I find the root Angular directory?

编辑:虽然这个问题最初是关于服务的,我现在知道服务应该包含在模块中,但核心问题在应用于导入模块时仍然有效。现在文档已经(有点)发展了,下面有一个更新的答案,"official" 方法可以做到这一点。

我想在 module/component 中引用一项服务。我所有的服务都在 /_services 目录中,当我知道我的服务总是在根目录下时,我不想向下遍历文件系统。如果我将我的组件移动到一个新的子目录中,我希望它能够适应这个简单的更改并且不需要返工。

换句话说,我可以改变这个吗:

import { ApiService } from './../../_services/api.service';

变成这样的东西?

import { ApiService } from '$APP_ROOT/_services/api.service';

您可以使用一些允许您执行此操作的库。

如果您正在使用 Webpack check this ,它将解决您的问题

Webpack 1

resolve: {
  root: [
    path.resolve(__dirname  + '/src')
  ]
}......

Webpack 2

resolve: {
  modules: [
    path.resolve(__dirname + '/src'),
    path.resolve(__dirname + '/node_modules')
  ]
}.....

After that you can use

import configureStore from "store/configureStore";

instead of the:

import configureStore from "../../store/configureStore";

如果您不使用 Webpack,您只需安装 Babel Root Import

// Usually
import SomeExample from '../../../some/example.js';
const OtherExample = require('../../../other/example.js');

// With Babel-Root-Importer
import SomeExample from '~/some/example.js';
const OtherExample = require('~/other/example.js');

仅仅几个月后,现在 angular 指南直接给出了答案。您可以使用以 "app" 开头的绝对路径从根目录引用模块。例如,如果你想加载共享模块,你只需使用这个导入:

import { SharedModule } from 'app/shared/shared.module';

这是指南中使用的:

https://angular.io/guide/ngmodule#app-routing

TypeScript 指南中也有关于此的部分:

https://www.typescriptlang.org/docs/handbook/module-resolution.html