Sometimes we want to access public methods in a service class from another service class in Angular. One method we can use to carry out such action is using Injector
.
Injectors
are part of Dependency Injection. Suppose we have two service class files: ServiceA
and ServiceB
. We want to access a method in ServiceB
from ServiceA
. Here is how we go about it:
In ServiceA
we import ServiceB
and also import Injector
from the @angular/core
package.
import {Injectable, Injector} from '@angular/core`;
import {ServiceB} from './serviceb`;
@Injectable({
providedIn: 'root',
})
export class ServiceA {
}
We the inject the Injector
into the constructor of the class:
import {Injectable, Injector} from '@angular/core`;
import {ServiceB} from './serviceb`;
@Injectable({
providedIn: 'root',
})
export class ServiceA {
constructor(private _injector: Injector){}
}
After that, we create a class method and use the injector’s get
method to getSomeData ServiceB
.
import {Injectable, Injector} from '@angular/core`;
import {ServiceB} from './serviceb`;
@Injectable({
providedIn: 'root',
})
export class ServiceA {
constructor(private _injector: Injector){}
injectServiceB(): ServiceB {
return this._injector.get(ServiceB)
}
}
Now we can access the public methods in ServiceB
from ServiceA
:
import {Injectable, Injector} from '@angular/core`;
import {ServiceB} from './serviceb`;
@Injectable({
providedIn: 'root',
})
export class ServiceA {
constructor(private _injector: Injector){}
injectServiceB(): ServiceB {
return this._injector.get(ServiceB)
}
getSomeDataFromServiceB() {
const serviceB = this.injectServiceB();
return serviceB.getSomeData();
}
}