我有两个组件,AComponent和BComponent,以及一个使用这两个组件的服务:
@Component({
selector: 'app-a',
templateUrl: './a.component.html',
styleUrls: ['./a.component.scss']
})
export class AComponent implements OnInit {
constructor(
private tabService: TabService
) {
}
ngOnInit() {
}
openB()
{
tabService.openTab(BComponent);
}
}
@Component({
selector: 'app-b',
templateUrl: './b.component.html',
styleUrls: ['./b.component.scss']
})
export class BComponent implements OnInit {
constructor(
private tabService: TabService
) {
}
ngOnInit() {
}
openA()
{
tabService.openTab(AComponent);
}
}
问题低于警告,这两个组件之间存在循环依赖关系。在这种情况下如何避免循环依赖?
想象有PersonListComponent和NewPersonComponent。在PersonListComponent内部,有一个按钮在选项卡中打开NewPersonComponent,在newPersonComponent中,有一个按钮在新选项卡中打开PersonListComponent。
给出示例,两个组件都应具有一个公共父对象。
将事件从子组件之一向上发送到父组件。然后从父组件调用该函数以在新选项卡中打开子组件之一。
组件A:
export class AComponent implements OnInit {
Output() OpenB: EventEmitter<any> = new EventEmitter();
}
B部分:
export class BComponent implements OnInit {
Output() OpenA: EventEmitter<any> = new EventEmitter();
}
父HTML:
<app-bcomponent (openA)="openComponent('A')"></app-bcomponent>
<app-acomponent (openB)="openComponent('B')"></app-acomponent>
家长ts:
openComponent(component) {
if (component === 'A') {
tabService.openTab(AComponent);
} else if (component === 'B') {
tabService.openTab(BComponent);
}
}
根据您在评论中所说的,您有两种解决方案:
1。使用对话框(Angular Material)例如
createUser()
方法将打开一个对话框,显示一个用于创建新用户的表单。
我无法在此处提供代码,因为太长了,无法显示Material Modal的工作原理。
2。为PersonList路由,为NewPerson路由另一条路由
在您的路由文件中,进行如下操作:
const routes: Routes = [
{ path: 'persons', component: PersonListComponent },
{ path: 'create', component: NewPersonComponent },
]
然后您可以在html文件中创建:
<a routerLink="/create" routerLinkActive="active"> Add </a>
一种解决方案,是在TabService中创建2个单独的方法:
openComponentA() {}
openComponentB() {}
然后这两个组件将不会互相导入。