角度2:将服务注入课堂 [英] Angular 2: Inject service into class

查看:105
本文介绍了角度2:将服务注入课堂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代表形状的角度类.我希望能够使用构造函数实例化该类的多个实例.

I have angular class that represents shape. I want to be able to instantiate multiple instances of that class using constructor.

构造函数采用表示该形状属性的多个参数.

The constructor takes multiple arguments representing properties of that shape.

constructor(public center: Point, public radius: number, fillColor: string,
    fillOpacity: number, strokeColor: string, strokeOpacity: number, zIndex: number)

在我的课堂内部,我想使用提供在地图上绘制形状的功能的服务.是否可以将该服务注入到我的类中,并且仍然以标准方式使用构造函数.

Inside my class I want to use service that provides capability to draw shapes on the map. Is it possible to inject that service into my class and still use constructor the standard way.

所以我想做下面的事情,让Angular自动解决注入的依赖性.

So I want to do something like below and have Angular automatically resolve injected dependency.

constructor(public center: GeoPoint, public radius: number, 
    fillColor: string, fillOpacity: number, strokeColor: string, strokeOpacity: number, 
    zIndex: number, @Inject(DrawingService) drawingService: DrawingService)

推荐答案

我已经设法解决了我的问题.

I've managed to resolve my problem.

Angular 2-4提供了反射式注入器,该注入器允许在构造函数参数之外注入依赖项.

Angular 2 - 4 provides reflective injector that allows to inject dependencies outside of constructor parameters.

我要做的就是从@angular/core导入Reflective注入器.

All I had to do was to import Reflective injector from @angular/core.

import {ReflectiveInjector} from '@angular/core';

然后:

let injector = ReflectiveInjector.resolveAndCreate([DrawingService]);
this.drawingApi = injector.get(DrawingService);

该类甚至不必使用@Injectable装饰器进行装饰. 唯一的问题是,我必须提供DrawingService的所有依赖关系以及所有嵌套的依赖关系,因此很难维护.

The class doesn't even have to be decorated with the @Injectable decorator. The only problem is that I have to provide all dependencies for DrawingService and all the nested dependencies, so that is hard to maintain.

编辑:

Angular 5

Angular 5

import { Injector } from "@angular/core";

const injector = Injector.create([
    { provide: DrawingService }
]);
this.drawingApi = injector.get(DrawingService);

角度6

import { Injector } from "@angular/core";

const injector = Injector.create({ 
  providers: [ 
    { provide: DrawingService },
  ]
});
this.drawingApi = injector.get(DrawingService);

这篇关于角度2:将服务注入课堂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆