在我的 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');
第二个组件令牌:component-b-token.ts
export const COMPONENT_B_TOKEN = new InjectionToken<any>('ComponentBToken');
然后在模块中提供组件:
providers: [
RenderService,
{ provide: COMPONENT_A_TOKEN, useValue: ComponentA },
{ provide: COMPONENT_B_TOKEN, useValue: ComponentB}
]
这允许我们注入组件类:
@Component({
selector: 'app-a',
templateUrl: './a.component.html',
styleUrls: ['./a.component.scss']
})
export class ComponentA {
constructor(@Inject(COMPONENT_B_TOKEN) private componentB) {
}
}