在Angular中,当模型之间存在循环依赖时,可以采用以下方法进行解决:
// 模块A
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ModuleB } from './module-b';
@NgModule({
imports: [
CommonModule,
ModuleB
],
declarations: [ComponentA],
exports: [ComponentA]
})
export class ModuleA { }
// 模块B
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ModuleA } from './module-a';
@NgModule({
imports: [
CommonModule,
ModuleA
],
declarations: [ComponentB],
exports: [ComponentB]
})
export class ModuleB { }
// 服务
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private dataSubject = new Subject();
data$ = this.dataSubject.asObservable();
setData(data: string) {
this.dataSubject.next(data);
}
}
// 模块A
import { Component } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-component-a',
template: `
`
})
export class ComponentA {
constructor(private sharedService: SharedService) { }
sendData() {
this.sharedService.setData('Data from Component A');
}
}
// 模块B
import { Component, OnInit } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-component-b',
template: `
{{ data }}
`
})
export class ComponentB implements OnInit {
data: string;
constructor(private sharedService: SharedService) { }
ngOnInit() {
this.sharedService.data$.subscribe(data => {
this.data = data;
});
}
}
通过以上两种方法,可以解决Angular中模型之间的循环依赖问题。