[英]Angular 2 service injection in class with no decorator
I am trying to build a simple mobile game using Ionic and therefore Angular2. 我正在尝试使用Ionic和Angular2构建一个简单的移动游戏。 I am new to both.
我是两个新手。
I want to inject a service (FieldService) in the constructor of a non-component class (Field). 我想在非组件类(Field)的构造函数中注入服务(FieldService)。 The injection does not work and console.log (in field.ts) always returns undefined (everything else works fine).
注入不起作用,console.log(在field.ts中)总是返回undefined(其他一切正常)。
I read countless articles about that and I feel like I understood how it works but can't seem to fix my problem in 2 days. 我阅读了无数关于这方面的文章,我觉得我理解它是如何工作的,但似乎无法在2天内解决我的问题。 Any help would be greatly appreciated.
任何帮助将不胜感激。
Structure 结构体
- app
- app.module.ts
- ...
- models
- field.ts
- components
- field.component.ts
- services
- field.service.ts
app.module.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 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 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 field.Service.ts
import { Injectable } from '@angular/core';
import 'rxjs/Rx';
@Injectable()
export class FieldService {
constructor() { }
}
Injection doesn't work for arbitrary classes, it only works for classes created by DI. 注入不适用于任意类,它仅适用于DI创建的类。
If you add @Injectable()
on top of export class Field {
and add Field
to providers and injecti it somewhere it might work. 如果你在
export class Field {
之上添加@Injectable()
并将Field
添加到提供者并在某处注入它可能会起作用。
Another point is that number
(and other native types) are not supported for constructor parameters of injectables without @Inject(...)
decorators (and matching providers). 另一点是,没有
@Inject(...)
装饰器(和匹配的提供者)的注入的构造函数参数不支持number
(和其他本机类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.