2017-07-06 16 views
0

我有一个类如下不与@Injectable是有可能使用一个服务成打字稿类在角2+

export class A extends B { 

    calculateTotal(): number { 
     //Implementation 
    } 
} 

上述功能calculateTotal需要使用该注释的服务注释与@Injectable能够获得一些值来执行一些总数。问题是:可以将该服务用于该课程吗?

阿什利

+0

是的,它是好的和记录:https://angular.io/guide/dependency-injection。你能否详细说明你的问题?你在问什么不太清楚。 –

+0

@PaoloStefan编辑我的问题 – ashley

回答

1

有不同的方式来获得注入class A一个SomeService实例。我使用的是在离子2是:

  • 如果类A可以是一个组件,该@Component装饰添加到它的定义和providers元数据给它;
  • 导入class A定义文件中的服务定义;
  • 将构造方法添加到class A并将服务实例声明为参数。

例如,假设服务类被命名为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 
    } 
} 

的更多信息可在the official docs