ashley
ashley

Reputation: 1038

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

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. Question is: is it ok to use that service into that class?

Ashley

Upvotes: 0

Views: 40

Answers (1)

Paolo Stefan
Paolo Stefan

Reputation: 10263

There are different ways to get one SomeService instance injected into class A. The one I use e.g. in Ionic 2 is:

  • if class A can be a Component, add the @Component decorator to its definition and the providers metadata to it;
  • import the service definition in the class A definition file;
  • add a constructor method to class A and declare a service instance as argument.

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:

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.

Upvotes: 1

Related Questions