Angular 2 injection services in the classroom without a decorator

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

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

I read countless articles about this, and it seems to me that I understood how it works, but cannot solve the 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() { }

}
+4
source share
1 answer

, , DI.

@Injectable() export class Field { Field , -, .

, number ( ) @Inject(...) ( ).

+2

Source: https://habr.com/ru/post/1659228/


All Articles