Ket*_*201 2 angular2-modules angular
我是Angular 2的初学者,我正在尝试了解如何从功能模块中导出类,并将其导入到我的主模块中.
当我尝试在打字稿中编译它时,我收到以下两个错误:
app/app.component.ts(11,21):错误TS2304:找不到名称'AddService'.
app/app.module.ts(4,9):错误TS2305:模块'"C:/angular/app/add/arithmetic.module"'没有导出成员'AddService'.
我的树很简单:
/
index.html
package.json
systemjs.config.js
tsconfig.json
typings.json
app/
app.component.html
app.component.ts
app.module.ts
main.ts
add/
add.service.ts
arithmetic.module.ts
Run Code Online (Sandbox Code Playgroud)
有趣的部分如下:
app.module.ts:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
// this next line generates an error from typescript compiler:
// app/app.module.ts(4,9): error TS2305: Module
// '"C:/angular/app/add/arithmetic.module"' has no exported
// member 'AddService'.
import {AddService} from './add/arithmetic.module';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent, AddService],
bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
calculate() {
// this next line generates the error:
// app/app.component.ts(11,21):
// error TS2304: Cannot find name 'AddService'.
var c = new AddService();
var x = c.addTwoNumbers(3, 5);
console.log(x);
}
}
Run Code Online (Sandbox Code Playgroud)
arithmetic.module.ts
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {AddService} from './add.service';
@NgModule({
imports: [CommonModule],
exports: [AddService]
})
export default class ArithemeticModule { }
Run Code Online (Sandbox Code Playgroud)
add.service.ts
export class AddService {
addTwoNumbers(a: number, b: number) : number {
return a + b;
}
}
Run Code Online (Sandbox Code Playgroud)
这真的令人沮丧,因为
1)我正在导出AddService - 它被标记为'export',并且从ArithmeticModule中我将它标记为使用@NgModule元数据导出.
2)我从我的主模块中导入[涉嫌]导出的AddService类,因此AddService应该可用,因为它是从ArithmeticModule导出的
如果我直接从组件中导入AddService,它工作正常,但这不是我想要的:我想从我的主模块导入类,并利用该模块的导出,就像我们对Angular的模块一样(例如,BrowserModule和FormsModule).@NgModule的文档说我们应该能够做到这一点 - 从我的功能模块导入一次到我的主模块,然后它可以在整个主模块中使用.
有人能告诉我我做错了什么吗?或者我误解了应该使用哪些模块?
Gün*_*uer 10
对于服务使用providers: [...],它们将被添加到根注入器(来自非延迟加载的模块).
exports: [] 用于导出指令,组件和管道的指令,组件,管道和模块.