如何将服务注入类(不是组件) [英] How to inject service into class (not component)

查看:52
本文介绍了如何将服务注入类(不是组件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将服务注入到不是组件的类中.

I want to inject a service into a class that is not a component.

例如:

我的服务

import {Injectable} from '@angular/core';
@Injectable()
export class myService {
  dosomething() {
    // implementation
  }
}

MyClass

import { myService } from './myService'
export class MyClass {
  constructor(private myservice:myService) {

  }
  test() {
     this.myservice.dosomething();
  }
}

此解决方案不起作用(我认为是因为尚未实例化MyClass).

This solution doesn't work (I think because MyClass hasn't been instantiated yet).

在类(不是组件)中还有其他使用服务的方法吗?还是您会认为我的代码设计不合适(在不是组件的类中使用服务)?

Is there another way to use a service in a class (not component)? Or would you consider my code design as inappropriate (to use a service in a class which is not a component)?

谢谢.

推荐答案

注入仅适用于通过Angulars依赖注入(DI)实例化的类.

Injections only works with classes that are instantiated by Angulars dependency injection (DI).

  1. 您需要
    • @Injectable()添加到MyClass
    • 在组件或NgModule中提供<​​c0>像providers: [MyClass]一样.
  1. You need to
    • add @Injectable() to MyClass and
    • provide MyClass like providers: [MyClass] in a component or NgModule.

然后在某个位置注入MyClass时,通过DI实例化一个MyService实例(在第一次注入之前)会将该实例传递给MyClass.

When you then inject MyClass somewhere, a MyService instance gets passed to MyClass when it is instantiated by DI (before it is injected the first time).

  1. 另一种方法是配置自定义注入器,例如

constructor(private injector:Injector) { 
  let resolvedProviders = ReflectiveInjector.resolve([MyClass]);
  let childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);

  let myClass : MyClass = childInjector.get(MyClass);
}

这样,myClass将成为MyClass实例,由Angulars DI实例化,并且myService在实例化时将注入到MyClass中. 另请参见在指令内手动从Injector获取依赖项

This way myClass will be a MyClass instance, instantiated by Angulars DI, and myService will be injected to MyClass when instantiated.
See also Getting dependency from Injector manually inside a directive

  1. 另一种方法是自己创建实例:

constructor(ms:myService)
let myClass = new MyClass(ms);

这篇关于如何将服务注入类(不是组件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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