[英]Angular 2 service injection in class with no decorator
我正在尝试使用Ionic和Angular2构建一个简单的移动游戏。 我是两个新手。
我想在非组件类(Field)的构造函数中注入服务(FieldService)。 注入不起作用,console.log(在field.ts中)总是返回undefined(其他一切正常)。
我阅读了无数关于这方面的文章,我觉得我理解它是如何工作的,但似乎无法在2天内解决我的问题。 任何帮助将不胜感激。
结构体
- app
- app.module.ts
- ...
- models
- field.ts
- components
- field.component.ts
- services
- field.service.ts
app.module.ts
import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { FieldComponent } from '../components/field.component';
import { FieldService } from '../services/field.service';
@NgModule({
declarations: [
MyApp,
FieldComponent,
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
],
providers: [FieldService]
})
export class AppModule {}
field.component.ts
import { Component } from '@angular/core';
import { Field } from '../models/field';
@Component({
selector: 'field',
templateUrl: 'field.component.html',
styles: []
})
export class FieldComponent {
field: Field;
constructor() {
this.field = new Field(3, 3, 3);
}
}
field.ts
import { Inject } from '@angular/core';
import { FieldService } from '../services/field.service';
export class Field implements OnInit {
constructor(nb_lots: number, nb_layers: number, diamonds_to_add: number, fieldService: FieldService) {
console.log(fieldService);
...
}
}
field.Service.ts
import { Injectable } from '@angular/core';
import 'rxjs/Rx';
@Injectable()
export class FieldService {
constructor() { }
}
注入不适用于任意类,它仅适用于DI创建的类。
如果你在export class Field {
之上添加@Injectable()
并将Field
添加到提供者并在某处注入它可能会起作用。
另一点是,没有@Inject(...)
装饰器(和匹配的提供者)的注入的构造函数参数不支持number
(和其他本机类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.