Reputation: 1185
I'm a longtime Angular dev now trying to learn the standalone version. How do I inject a service into another service without a providers
array in the NgModule. Is my only choice using providedIn
in the Injectable
declaration?
Upvotes: 3
Views: 1567
Reputation: 56002
If your service is not providedIn: root
, then you must be adding the service to the providers array of some standalone component (in-order to use it). You need to add the second service to the same array, so that the service has its own instance of the second service.
import { Component, inject } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { FirstService } from './app/first.service';
import { SecondService } from './app/second.service';
@Component({
selector: 'app-root',
standalone: true,
providers: [FirstService, SecondService],
template: `
<h1>Hello from {{ name }}!</h1>
<a target="_blank" href="https://angular.dev/overview">
Learn more about Angular
</a>
`,
})
export class App {
name = 'Angular';
firstService = inject(FirstService);
}
bootstrapApplication(App);
Above method is the best approach, but you have other options also.
import { Injectable } from '@angular/core';
import { SecondService } from './second.service';
@Injectable()
export class FirstService extends SecondService {
constructor(protected http: HttpClient) {
this.test(http);
}
}
import { Injectable } from '@angular/core';
@Injectable()
export class SecondService {
constructor(protected http: HttpClient) {}
test() {
console.log('from second service');
}
}
You will have to access the second service as a class and only through the first service, it is not visible in angular DI, and you will have to provider the dependencies to the service (E.g.: HttpClient)
import { Injectable } from '@angular/core';
import { SecondService } from './second.service';
@Injectable()
export class FirstService {
secondService!: SecondService;
constructor(protected http: HttpClient) {
this.secondService = new SecondService(http); // <- create a new instance
// this exists only inside first service.
}
}
Upvotes: 0