简体   繁体   English

是否可以在Angular 2+中将服务用于Typescript类

[英]is it possible to use a service into a typescript class in Angular 2+

I have a class as follows which is not annotated with @Injectable 我有一个如下类,未使用@Injectable进行注释

export class A extends B {

    calculateTotal(): number {
        //Implementation
    }
} 

The above function calculateTotal needs to use a service which is annotated with @Injectable to be able to get some values to perform some totals. 上面的函数calculateTotal需要使用带有@Injectable注释的服务,以便能够获取一些值以执行总计。 Question is: is it ok to use that service into that class? 问题是:可以在该类中使用该服务吗?

Ashley 阿什利

There are different ways to get one SomeService instance injected into class A . 有多种方法可以将一个SomeService实例注入到class A The one I use eg in Ionic 2 is: 我在离子2中使用的一个是:

  • if class A can be a Component, add the @Component decorator to its definition and the providers metadata to it; 如果类A可以是Component,则在其定义中添加@Component装饰器,并在其定义中添加providers元数据;
  • import the service definition in the class A definition file; 将服务定义导入到class A定义文件中;
  • add a constructor method to class A and declare a service instance as argument. class A添加构造函数方法,并将服务实例声明为参数。

For example, assuming that the service class is named SomeService and is defined in the file some.service.ts in the same directory as the current source file: 例如,假设服务类名为SomeService并且在与当前源文件相同目录中的some.service.ts文件中定义:

import { Component } from '@angular/core';
import { SomeService } from './some.service';

@Component({
    providers: [ SomeService ]
})
export class A extends B {

    constructor( public s:SomeService ){}

    otherMethod(){
        this.s; // SomeService is accessible like this
    }
}

More information is available in the official docs . 官方文档中提供了更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM