gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:08:36 24 4
gpt4 key购买 nike

如何从 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com