默认情况下,我的组件中的依赖项注入不起作用 我必须明确地添加@Inject装饰器
我的应用程序包含多个文件。
主要:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
import 'zone.js';
import 'reflect-metadata';
platformBrowserDynamic().bootstrapModule(AppModule);
app.module.ts :
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './appcomponent/app.component';
import { PostComponent } from './postcomponent/post.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MyService } from './my.service';
@NgModule({
declarations: [
AppComponent,
PostComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [MyService],
bootstrap: [AppComponent]
})
export class AppModule {}
appcomponent / app.component.ts
import { Component, Inject } from '@angular/core';
@Component({
selector: 'app-component',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {}
postcomponent / post.component.ts
import { Component, Inject } from '@angular/core';
import { MyService } from "../my.service";
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent {
constructor(private service: MyService) {
}
}
my.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
send(message: string): void {
alert(message);
}
}
ts.config.json
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es6",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true, // Workaround for https://github.com/angular/angular/issues/17863. Remove this if you upgrade to a fixed version of Angular.
"module": "es2015",
"moduleResolution": "node",
"types": [
"node"
]
},
"exclude": [
"node_modules",
"wwwroot"
]
}
的package.json
{
"name": "angulartest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
抛出异常
bundle.js:sourcemap:31848未捕获错误:无法解析所有参数 对于PostComponent :(?)。
我必须使用
constructor(@Inject(MyService) private service: MyService) {
而不是
constructor(private service: MyService) {
为什么?
我读过https://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html 如果类具有装饰器,则angular会自动添加依赖项注入的元数据。 但我的PostComponent类有一个装饰器@Component。