【问题标题】:Angular 2 service injection in class with no decorator没有装饰器的类中的Angular 2服务注入
【发布时间】:2016-10-28 20:42:48
【问题描述】:

我正在尝试使用 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() { }

}

【问题讨论】:

    标签: angular ionic-framework code-injection


    【解决方案1】:

    注入不适用于任意类,它只适用于 DI 创建的类。

    如果您在export class Field { 之上添加@Injectable() 并将Field 添加到提供程序并将其注入它可能会工作的地方。

    另外一点是,没有@Inject(...) 装饰器(和匹配的提供者)的注入的构造函数参数不支持number(和其他原生类型)。

    【讨论】:

    • 这可以解释为什么为了让它工作而失去了这么多头发。我尝试了你的解决方案制作 Field @Injectable,我删除了其他参数并且它确实有效(它变成在另一个服务中注入一个服务)。这不是我真正打算做的,但会找到一种方法让它发挥作用。谢谢。
    • :D 没有奇迹发生。 Angular2 DI 所做的是分析具有 @Injectable()@Component()@Directive()@Pipe() 装饰器的类的构造函数,当它创建此类类之一的实例时,它会查找其提供者以进行匹配在调用new SomeClass(....) 时传递给构造函数的实例。您可以注入Injector,然后调用injector.get(...) 命令式地获取实例。不过,您每次都会得到相同的实例。
    猜你喜欢
    • 2017-05-20
    • 2020-01-18
    • 2018-07-30
    • 2019-03-10
    • 2017-08-22
    • 1970-01-01
    • 2016-02-02
    • 2016-10-20
    • 1970-01-01
    相关资源
    最近更新 更多