当一个服务需要导入另一个服务时"cycle dependency"如何避免错误



我正在编写一个Angular前端,我希望在其中收集对同一服务中后端的所有HTTP调用。

失败的提交就在这里(只有一个更改可以使其工作(,我在下面总结。

所以,我得到了这个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);
}
(...)

到目前为止,一切都很好。现在,我想让其他服务依赖于BackendService.get方法,它将是处理超时、错误处理和其他事情的中心位置。

现在,当我在另一个服务中定义这个服务时,比如:

import { Injectable } from '@angular/core';
import { BackendService } from './backend.service';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(
private backend: BackendService,  // <-- here!
) { }

然后编译没有错误,但我得到以下控制台错误:

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

其中user-panel.component.ts正在导入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();
}
}

所以问题:如何将一个服务导入另一个服务?

评论:

  • 我看到了关于真正的循环依赖关系的其他问题,但在这里我真的精简了我的示例,并且在我的服务中没有其他依赖关系。我在网上也找不到任何接近的东西。

  • 我觉得这可能与@Injectable的内容有关,尽管清空它并没有带来明显的改善。(

;碎屑";正在使用Injector获取对新后端服务的引用

private backend: BackendService
constructor (injector:Injector) {
this.backend = injector.get(BackendService);
}

最新更新