angular - 如何在模块中导出服务?

标签 angular typescript

如何从 Angular 2 中的模块导出服务?

这个想法是,当我导入另一个组件时,我希望导入不知道实际的服务位置,应该是模块的责任来管理它

核心模块.ts:

import {
NgModule,
Optional, SkipSelf } from '@angular/core';
import { CommonModule } from '@angular/common';

import { MyApi } from './Api/myApi.service';

import { AuthenticationModule } from './authentication/authentication.module';

@NgModule({
imports: [
    CommonModule,
    AuthenticationModule
],
providers: [
    MyApi
],
exports: [MyApi, AuthenticationModule]
})
export class CoreModule {
constructor( @Optional() @SkipSelf() parentModule: CoreModule) {
    if (parentModule) {
    throw new Error(
        'CoreModule is already loaded. Import it in the AppModule only');
    }
}

}

App.component.ts:
import { Router, ActivatedRoute } from '@angular/router';
import { Component, ViewContainerRef, OnInit } from '@angular/core';

import { MyApi } from 'core.module'; //i want this to be the core module import, not './core/api/myApi.service'

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor ( public service: MyApi) {
        service.doStuff()
    }
}

但在上面的代码示例中,它告诉我 MyApi 不是由 Core.module 导出的。

这有点伪代码,所以请原谅我犯的小错误:)

最佳答案

你可以做两件事来让你的导入更简洁:

  • 您可以从入口点文件中导出所有内容(按照惯例,通常称为 index.ts),然后导入您从该文件中导出的任何类:
    import { NgModule } from '@angular/core';
    import { ApiService } from 'path/to/api.service';
    @NgModule({ ... })
    export class CoreModule {}
    export * from 'path/to/api.service';
    

    这样您就可以同时导入 CoreModuleApiService从这样的同一条路线:
    import { CoreModule, ApiService } from 'path/to/core.module;'
    

    因此,您对所有模块依赖项都有一个共同的入口点。
  • 如果你的模块嵌套很深,或者你想从一个可能会在几个目录中来回切换的位置导入它,你总是可以在你的主目录 tsconfig.json 中为该路径创建一个别名。文件,在 compilerOptions.paths 下:
    {
      "compilerOptions": {
        // ...
        "paths": {
          "@app-core": ["app/path/to/deeply/nested/core.module"]
        }
      }
    }
    

    然后改用该别名:
    import { CoreModule, ApiService } from '@app-core'
    
  • 关于angular - 如何在模块中导出服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47906113/

    相关文章:

    typescript - 如何将泛型限制为联合?

    javascript - Typescript 声明已定义字符串或任何字符串的类型

    angular - 获取未捕获错误 : Can't resolve all parameters for

    javascript - RxJS skipWhile bool 值为真

    forms - angular2通过按enter而不提交按钮提交表单

    使用 toHaveBeenCalled 进行 Angular Jasmine 测试

    angular - Chrome 浏览器不支持图像方向属性

    typescript - 如何模拟包含正斜杠的模块?

    http - 如何使用 angular2 http API 跟踪上传/下载进度

    angular - 如何对 Angular 2 路由参数进行单元测试