【问题标题】:Angular circular dependency - Components call each otherAngular 循环依赖 - 组件相互调用
【发布时间】:2020-07-02 11:13:55
【问题描述】:

在我的 Angular 应用程序中,我有 2 个可以作为模态打开彼此的组件。 从组件 A 可以打开组件 B,从组件 B 可以打开组件 A。 如何在没有循环依赖的情况下实现这一目标? 我尝试将模态调用移至服务,但两个组件都需要注入此服务,并且我再次具有循环依赖。

我还阅读了一些关于使用 forwardRef 进行注入的内容,但我无法让它工作。 我尝试在组件的构造函数中注入这样的服务:

@Inject(forwardRef(() => CircularService)) private circularService: CircularService

【问题讨论】:

  • 如果你创建一个modalsService,使用open方法,动态创建modals,那么A和B可以注入服务,打开任何modals都没有问题

标签: angular dependency-injection circular-dependency


【解决方案1】:

我为您的问题提供了解决方案,我们可以使用 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__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) {
    }
}

【讨论】:

  • 谢谢,这就像一个魅力!我其实只需要一个 Token 就可以打破循环
猜你喜欢
  • 1970-01-01
  • 2011-09-18
  • 1970-01-01
  • 2017-10-12
  • 2013-10-21
  • 2013-03-18
  • 2014-07-27
  • 2019-03-24
  • 2023-03-04
相关资源
最近更新 更多