2016-10-28 4 views
4

私はIonicを使用して、したがってAngular2を使って簡単なモバイルゲームを構築しようとしています。私は両方に新しいです。デコレータのないクラスでの角2サービスインジェクション

サービス(FieldService)を非コンポーネントクラス(Field)のコンストラクタに挿入したいと考えています。注射は機能せず、console.log(field.ts内)は常に定義されていません。

私はそれについての無数の記事を読んで、私はそれがどのように動作するのか理解しているように感じますが、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() { } 

} 

答えて

2

注入は、それが唯一のDIによって作成されたクラスのために働く、任意のクラスでは動作しません。

export class Field {の上に@Injectable()を追加し、プロバイダにFieldを追加して、それをどこかに注入すると、

number(および他のネイティブタイプ)は、@Inject(...)デコレータ(および対応するプロバイダ)がない注射用のコンストラクタパラメータではサポートされていません。

+0

私はあなたの解決策をField @注射可能にしました。私は他のパラメータを取り除いて動作します(別のサービスでサービスを注入するようになります)。それは本当に私がやろうとしたものではありませんが、それを機能させる方法を見つけるでしょう。ありがとう。 –

+0

:D魔法は起こっていません。 Angular2 DIは、 '@Injectable()'、 '@Component()'、 '@Directive()'、 '@Pipe()'デコレータを持つクラスのコンストラクタを解析し、そのようなクラスの1つは、 'new SomeClass(....)'を呼び出すときにインスタンスを一致させるためのプロバイダをコンストラクタに渡します。 'Injector'を注入して、' injector.get(...) 'を呼んでインスタンスを取得することができます。あなたは毎回同じインスタンスを取得します。 –

関連する問題