在 app.component 中使用核心模块的服务
consume Services from core module in app.component
大家好,我是 angular 2 的新人,我正在尝试将我在 angular.io 学到的所有东西都落实到位。
问题是我已经阅读了核心模块、服务、注射剂......和
如果我有这样的核心模块:
import { NgModule } from '@angular/core';
import { LoggerService } from './services/logger.service';
@NgModule({
exports: [
//components
LoggerComponent,
],
declarations: [LoggerComponent],
providers: [LoggerService],
})
export class CoreModule { }
和一个简单的 app.module 比如:
import { CoreModule } from './core/core.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
CoreModule,
BrowserModule,
HttpModule,
routerModule,
],
declarations: [
AppComponent,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
如何使用核心模块导出的LoggerService服务?我必须
import {LoggerService} from './core/services';
在我的 app.component 中?因为在 app.component 的构造函数中它不起作用
constructor(logger: LoggerService){}
我缺少什么?谢谢!
来自ngModule
documentation
providers : Provider[] Defines the set of injectable objects that are
available in the injector of this module.
换句话说,提供者将在模块内部而不是向外暴露。进一步阅读文档表明只有 directives/pipes/(components) 适用于 export/declare.
因此,要解决此问题,您需要直接引用更高级别模块中的服务,请注意,它将正确使用核心模块中的单独实例化服务非常酷,打破了我的预期。
app.module.ts
import {LoggerService} from './core/services';
@NgModule({<...>, providers: [<...>, LoggerService]})<...>
如果你打算拥有一堆共享服务,而不是使用 barrel 列出所有这些服务并进行一次性导入是合理的方法。
这是功能demo
大家好,我是 angular 2 的新人,我正在尝试将我在 angular.io 学到的所有东西都落实到位。 问题是我已经阅读了核心模块、服务、注射剂......和
如果我有这样的核心模块:
import { NgModule } from '@angular/core';
import { LoggerService } from './services/logger.service';
@NgModule({
exports: [
//components
LoggerComponent,
],
declarations: [LoggerComponent],
providers: [LoggerService],
})
export class CoreModule { }
和一个简单的 app.module 比如:
import { CoreModule } from './core/core.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
CoreModule,
BrowserModule,
HttpModule,
routerModule,
],
declarations: [
AppComponent,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
如何使用核心模块导出的LoggerService服务?我必须
import {LoggerService} from './core/services';
在我的 app.component 中?因为在 app.component 的构造函数中它不起作用
constructor(logger: LoggerService){}
我缺少什么?谢谢!
来自ngModule
documentation
providers : Provider[] Defines the set of injectable objects that are available in the injector of this module.
换句话说,提供者将在模块内部而不是向外暴露。进一步阅读文档表明只有 directives/pipes/(components) 适用于 export/declare.
因此,要解决此问题,您需要直接引用更高级别模块中的服务,请注意,它将正确使用核心模块中的单独实例化服务非常酷,打破了我的预期。
app.module.ts
import {LoggerService} from './core/services';
@NgModule({<...>, providers: [<...>, LoggerService]})<...>
如果你打算拥有一堆共享服务,而不是使用 barrel 列出所有这些服务并进行一次性导入是合理的方法。
这是功能demo