Angular 循环依赖 - 组件相互调用
Angular circular dependency - Components call each other
在我的 Angular 应用程序中,我有 2 个组件可以作为模式相互打开。
从组件 A 可以打开组件 B,从组件 B 可以打开组件 A。
我怎样才能在没有循环依赖的情况下实现这一点?
我尝试将模态调用移动到一个服务,但是两个组件都需要注入这个服务,我又遇到了循环依赖。
我还阅读了一些关于使用 forwardRef 注入的内容,但我无法让它工作。
我试图在组件的构造函数中注入这样的服务:
@Inject(forwardRef(() => CircularService)) private circularService: CircularService
我有解决您问题的方法,我们可以使用 InjectionTokens 并在共享模块中提供它们。
第一个组件标记:component-a-token.ts
export const COMPONENT_A_TOKEN = new InjectionToken<any>('ComponentAToken');
第二个组件令牌:组件-b-token.ts
export const COMPONENT_B_TOKEN = new InjectionToken<any>('ComponentBToken');
然后在模块中提供组件:
providers: [
RenderService,
{ provide: COMPONENT_A_TOKEN, useValue: ComponentA },
{ provide: COMPONENT__TOKEN, useValue: ComponentB}
]
这允许我们注入组件class:
@Component({
selector: 'app-a',
templateUrl: './a.component.html',
styleUrls: ['./a.component.scss']
})
export class ComponentA {
constructor(@Inject(COMPONENT_B_TOKEN) private componentB) {
}
}
在我的 Angular 应用程序中,我有 2 个组件可以作为模式相互打开。 从组件 A 可以打开组件 B,从组件 B 可以打开组件 A。 我怎样才能在没有循环依赖的情况下实现这一点? 我尝试将模态调用移动到一个服务,但是两个组件都需要注入这个服务,我又遇到了循环依赖。
我还阅读了一些关于使用 forwardRef 注入的内容,但我无法让它工作。 我试图在组件的构造函数中注入这样的服务:
@Inject(forwardRef(() => CircularService)) private circularService: CircularService
我有解决您问题的方法,我们可以使用 InjectionTokens 并在共享模块中提供它们。 第一个组件标记:component-a-token.ts
export const COMPONENT_A_TOKEN = new InjectionToken<any>('ComponentAToken');
第二个组件令牌:组件-b-token.ts
export const COMPONENT_B_TOKEN = new InjectionToken<any>('ComponentBToken');
然后在模块中提供组件:
providers: [
RenderService,
{ provide: COMPONENT_A_TOKEN, useValue: ComponentA },
{ provide: COMPONENT__TOKEN, useValue: ComponentB}
]
这允许我们注入组件class:
@Component({
selector: 'app-a',
templateUrl: './a.component.html',
styleUrls: ['./a.component.scss']
})
export class ComponentA {
constructor(@Inject(COMPONENT_B_TOKEN) private componentB) {
}
}