Angular 5.当彼此导入类时,打字稿中的循环依赖性



在Angular 5应用程序中使用打字稿。当尝试在组件之间实现通信时,我面对称为循环依赖关系的问题。有两个组件radioradio-group

<radio-group [(value)]='selected'>
  <radio value='1'></radio>
  <radio value='2'></radio>
  <radio value='3'></radio>
</radio-group>

当用户选择和取消选择项目时,他们相互通信。

组件实现示例放射线群:

import { Component, forwardRef, Input, Optional, ContentChildren, 
QueryList, EventEmitter, Output, ChangeDetectorRef, ChangeDetectionStrategy, AfterContentInit, OnChanges } from '@angular/core';
import { RadioGroup } from './radio-group.component';
@Component({
  selector: 'radio',
  styles: [`:host{cursor:pointer;}`],
  template: `<div (click)='check()'>
  <span *ngIf='!checked'>⚪️</span>
  <span *ngIf='checked'>🔘</span>
  <span>Click me. Value: {{value}} Checked: {{checked}}</span>
  </div>`,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class Radio  {
  @Input() value: any;
  checked = false;
  private _radioGroup: RadioGroup;
  constructor(@Optional() radioGroup: RadioGroup, public cd: ChangeDetectorRef){
    this._radioGroup = radioGroup;
  }
  check(){
    this.checked = true;
    if(this._radioGroup){
      this._radioGroup.selected = this;
    }
    this.markForCheck();
  }
  markForCheck(){
    this.cd.markForCheck();
  }
}

radioComponent:

import { Component, forwardRef, Input, Optional, ContentChildren, QueryList, EventEmitter, Output, ChangeDetectorRef, ChangeDetectionStrategy, AfterContentInit, OnChanges } from '@angular/core';
import { Radio } from './radio.component';
@Component({
  selector: 'radio-group',
  template: `<ng-content></ng-content>`,
})
export class RadioGroup implements AfterContentInit, OnChanges{
  set selected (component:Radio){
    this._selected = component;
    this.valueChange.emit(component.value);
  } 
  private _selected:Radio = null;
  @Input() value:any;
  @Output() valueChange = new EventEmitter();
  @ContentChildren(forwardRef(() => Radio)) radioComponents: QueryList<Radio>;
  ngAfterContentInit() { this.checkParentComponents();}
  ngOnChanges(){ this.checkParentComponents();}
  checkParentComponents():void{
    this.radioComponents 
    && this.radioComponents.forEach(item=>{
        item.checked = item.value==this.value;
        if(item.checked){ this._selected = item;}
        item.markForCheck();
    });
  }
}

在线示例

使用一个文件(stackblitz.com(中的所有声明的工作示例

与分开文件(stackblitz.com(的破碎示例

问题

我如何通过循环依赖性解决此问题,并将所有组件和实现放入分离的文件中?随着时间组件变得沉重,如何将它们切成碎片?

您不应从Radio编辑RadioGroup属性。儿童和父零件之间的通信应通过@Input@Output进行。

因此,从Radio构造函数中删除RadioGroup。相反,您可以进行以下操作,

import { 
   Component, 
   Input,
   EventEmitter,
   Output,
   ChangeDetectorRef,
   ChangeDetectionStrategy
} from '@angular/core';
@Component({
  selector: 'radio',
  styles: [`:host{cursor:pointer;}`],
  template: `
     <div (click)='check()'>
        <span *ngIf='!checked'>⚪️</span>
        <span *ngIf='checked'>🔘</span>
        <span>Click me. Value: {{value}} Checked: {{checked}}</span>
     </div>`,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class Radio  {
  @Input() value: any;
  @Output() valueChange: EventEmitter<any> = new EventEmitter();
  checked = false;
  constructor(public cd: ChangeDetectorRef){
  }
  check(){
    this.checked = true;
    this.valueChange.emit(this.value);
    this.markForCheck();
  }
  markForCheck(){
    this.cd.markForCheck();
  }
}

RadioGroup.component

@Component({
  selector: 'radio-group',
  template: `<ng-content></ng-content>`,
})
export class RadioGroup implements AfterContentInit, OnChanges, OnDestroy {
  set selected(component: Radio) {
    this._selected = component;
    this.valueChange.emit(component.value);
  }
  private _selected: Radio = null;
  @Input() value: any;
  @Output() valueChange = new EventEmitter();
  @ContentChildren(forwardRef(() => Radio)) radioComponents: QueryList<Radio>;
  subscriptionList = [];
  ngAfterContentInit() { this.checkParentComponents(); }
  ngOnChanges() { this.checkParentComponents(); }
  checkParentComponents(): void {
    if (this.radioComponents) {
      this.subscriptionList = this.radioComponents.map(item => {
        item.checked = item.value === this.value;
        if (item.checked) { this._selected = item; }
        item.markForCheck();
        // subscribe to each child "valueChange" event and return these subscriptions.
        return item.valueChange.subscription(value => this.selected = value);
      });
    }
  }
  ngOnDestroy() {
      // don't forget to unsubscribe.
      if (this.subscriptionList && this.subscriptionList.length ) {
          this.subscriptionList.forEach(sub => sub.unsubscribe());
      }
  }
}

尝试在无线电 Component构造器而不是

constructor(@Optional() radioGroup: RadioGroup, public cd: ChangeDetectorRef)

此代码

constructor(@Inject(forwardRef(() => RadioGroup)) radioGroup: RadioGroup, public cd: ChangeDetectorRef)

需要在组件之间设置通信

不能使用 @output @inputs ,使用providers。依赖性允许您在需要时覆盖在构造函数类中。

依赖项(angular.io(

避免循环依赖性(Angular.io(

readoygroup.component.ts:

import { RadioGroupBase } from './radio-group-base';
@Component({
  selector: 'radio-group',
  ...
  ==> providers: [{provide: RadioGroupBase, useExisting: RadioGroup}]
})
export class RadioGroup implements AfterContentInit, OnChanges{
...
}

radio.component.ts:

import { RadioGroupBase } from './radio-group-base';
@Component({
  selector: 'radio',
  ...
})
export class Radio  {
  constructor(
   ==> @Optional() radioGroup: RadioGroupBase, 
  ){
    //variable radioGroup will be undefined when there is no provider.
  }

射线组基准:

export class RadioGroupBase {
  selected: any;
}

工作解决方案:

https://stackblitz.com/edit/angular-gyqmve

使用共享服务https://angularfirebase.com/lessons/sharing-data-bete-ween-gangular-components-four-methods/部分:"无关组件:与服务共享数据"

Angular 2-使用共享服务

最新更新