我在角度项目中面临循环依赖。我遇到了许多解决方案,包括按照此处的说明从“单个文件”中导出所有依赖类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 dependencyServices depending on each other
但是,尽管使用了依赖注入,但是仍然有例外。下面是代码:
moduleA.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 { }
有人可以看一下代码和身份吗?谢谢
问题是,模块名称与模块本身导出在同一文件中。您应该创建一个单独的名为module-names.const.ts
的文件:
export const MODULE_A_NAME = 'Module A';
export const MODULE_B_NAME = 'Module B';
然后您可以在两个模块中导入此文件,而无需循环依赖:
import { MODULE_A_NAME } from "./module-names.const";
import { Injectable, Injector } from "@angular/core";
@Injectable({
providedIn: 'root'
})
export class ModuleB {
constructor(private injector: Injector) {
setTimeout(() => this.tempService = injector.get(MODULE_A_NAME));
}
}
但是,您想做什么?感觉上您在做某些绝对不应该做的事情。 (或与此相关的任何其他编程环境中)。我敢肯定,一旦使用--prod
标志编译了应用程序,您的模块名称就会有所不同,并且您尝试执行的操作将不再起作用