In my Angular front-end project, I am working on consolidating all HTTP calls to the back-end within a single service.
The commit causing issues can be found here (with just one change for it to work), and here is a summary of the changes.
I have a class called BackendService
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';
const backendUrl = 'http://localhost:5001/api/';
const statusEndpoint = '/status';
@Injectable({
providedIn: 'root'
})
export class BackendService {
// exposed Subject of this service
public status$ = new BehaviorSubject<BackendStatus>(defaultStatus);
constructor(
private http: HttpClient,
) { }
private updateStatus(): void {
this.get(statusEndpoint).subscribe(raw => { this.status$.next(raw); });
}
public get(endpoint: string): Observable<HttpResponse<any>> {
return this.http.get(backendUrl + endpoint);
}
(...)
Now, I aim to utilize the BackendService.get
method in other services to handle timeouts, error handling, and similar tasks centrally.
When I inject this service into another service like this:
import { Injectable } from '@angular/core';
import { BackendService } from './backend.service';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(
private backend: BackendService, // <-- here!
) { }
The compilation works without errors, but I encounter the following console error:
ERROR Error: Cannot instantiate cyclic dependency! AuthService
Angular 7
UserPanelComponent_Factory user-panel.component.ts:12
Angular 5
getNodeInjectable
instantiateAllDirectives
createDirectivesInstances
elementStart
element
AppComponent_Template app.component.html:4
Angular 20
core.js:6241:19
This issue occurs because user-panel.component.ts
imports AuthService
:
import { Component, OnInit } from '@angular/core';
import { AuthService, Credentials } from '../auth.service';
import { UserService, UserDetails } from '../user.service';
@Component({
selector: 'app-user-panel',
templateUrl: './user-panel.component.html',
styleUrls: ['./user-panel.component.scss']
})
export class UserPanelComponent implements OnInit {
public userDetails: UserDetails;
constructor(
public auth: AuthService,
public user: UserService,
) {}
ngOnInit(): void {
// trigger refresh from local storage once the component is ready
this.auth.initializeFromStorage();
}
onLogOut() {
this.auth.logUserOut();
}
}
So, how can I resolve this issue of importing a service into another service?
Additional Notes:
I have checked similar questions regarding cyclic dependencies, but my case seems isolated with no additional dependencies. I have not come across any relevant solutions online either.
I suspect the issue may be related to the implementation of
@Injectable
, although removing its content did not yield any noticeable improvements.