【发布时间】:2020-04-08 18:28:02
【问题描述】:
我在 Angular 项目中面临循环依赖。我遇到了许多解决方案,包括按照此处的说明从“单个文件”导出所有依赖类https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de 它没有用。所以我转向不同的解决方案,比如按照以下链接中的说明使用依赖注入:
How to solve the circular dependency Services depending on each other
但是尽管使用了依赖注入,还是有例外。 下面是代码:
模块A.ts
import { MODULE_B_NAME } from "./moduleB";
import { Injectable, Injector } from "@angular/core";
export const MODULE_A_NAME = 'Module A';
@Injectable({
providedIn: 'root'
})
export class ModuleA {
private tempService: any;
constructor(private injector: Injector) {
setTimeout(() => this.tempService = injector.get(MODULE_B_NAME));
}
public getName(): string {
this.tempService.getName();
return "we are forked";
}
}
moduleB.ts
import { MODULE_A_NAME } from "./moduleA";
import { Injectable, Injector } from "@angular/core";
export const MODULE_B_NAME = 'Module B';
@Injectable({
providedIn: 'root'
})
export class ModuleB {
private tempService: any;
constructor(private injector: Injector) {
setTimeout(() => this.tempService = injector.get(MODULE_A_NAME));
}
public getName(): string {
//this.tempService = this.injector.get(MODULE_A_NAME);
this.tempService.getName();
return "we are forked";
}
}
appComponent.ts
import { Component } from '@angular/core';
import { ModuleA } from './moduleA';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'test01';
getSomething() {
return ModuleA.name;
}
}
appModules.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ModuleA } from './moduleA';
import { ModuleB } from './moduleB';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [ModuleA, ModuleB],
bootstrap: [AppComponent]
})
export class AppModule { }
有人可以看看代码和身份有什么问题吗 谢谢
【问题讨论】:
-
为什么 2 个服务相互引用?他们有什么共同点?通常,如果您有循环依赖,则应该考虑更深层次的设计问题。重构代码,以便通过将通用代码抽象或移动到单个位置来打破循环依赖关系。如果没有相关的实际代码,很难说具体是什么样的。
标签: javascript angular typescript dependency-injection circular-dependency