简体   繁体   中英

Angular 2 service injection in class with no decorator

I am trying to build a simple mobile game using Ionic and therefore Angular2. I am new to both.

I want to inject a service (FieldService) in the constructor of a non-component class (Field). The injection does not work and console.log (in field.ts) always returns undefined (everything else works fine).

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. 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

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() { }

}

Injection doesn't work for arbitrary classes, it only works for classes created by DI.

If you add @Injectable() on top of export class Field { and add Field to providers and injecti it somewhere it might work.

Another point is that number (and other native types) are not supported for constructor parameters of injectables without @Inject(...) decorators (and matching providers).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM