如何从 angular 2 的模块导出服务?
这个想法是,当我导入另一个组件时,我希望导入与实际服务位置无关,应该是模块的责任来管理它
核心.module.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');
}
}
}
Run Code Online (Sandbox Code Playgroud)
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()
}
}
Run Code Online (Sandbox Code Playgroud)
但是在上面的代码示例中,它告诉我 Core.module 没有导出 MyApi。
这有点伪代码,所以请原谅我犯的小错误:)
您可以采取两件事来使导入更加简洁:
您可以从入口点文件(按照惯例通常称为index.ts)导出所有内容,然后导入从该文件导出的任何类:
import { NgModule } from '@angular/core';
import { ApiService } from 'path/to/api.service';
@NgModule({ ... })
export class CoreModule {}
export * from 'path/to/api.service';
Run Code Online (Sandbox Code Playgroud)
这样您就可以从同一路径导入CoreModule和 ,如下所示:ApiService
import { CoreModule, ApiService } from 'path/to/core.module;'
Run Code Online (Sandbox Code Playgroud)
因此,您的所有模块依赖项都有一个公共入口点。
如果您的模块是深度嵌套的,或者您想要从可能最终会在几个目录中来回移动的位置导入它,那么您始终可以在主文件中为该路径创建一个别名tsconfig.json,位于compilerOptions.paths:
{
"compilerOptions": {
// ...
"paths": {
"@app-core": ["app/path/to/deeply/nested/core.module"]
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用该别名代替:
import { CoreModule, ApiService } from '@app-core'
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
10340 次 |
| 最近记录: |