簡體   English   中英

在類中沒有裝飾器的Angular 2服務注入

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM