angular-将数据发送到子组件

时间:2020-01-06 13:56:47

标签: angular typescript

我有一个父级组件和三个子级组件

我通过这三个组件发送数据,并使用setTimeout来控制发送数据的时间

第一个组件持续5000毫秒

第二个组件持续10000毫秒

第三部分持续15000毫秒

在每个子组件中,我使用了一个微调器,当数据到达组件时,该微调器会隐藏

问题在于,当数据到达第一个组件时,其他组件的所有微调框也都隐藏了

export class AppComponent {
  public dataOne: string;
  public dataTwo: string;
  public dataThree: string;

  constructor() {
    setTimeout(() => {
      this.dataOne = "one";
    }, 5000);

    setTimeout(() => {
      this.dataTwo = "two";
    }, 10000);

    setTimeout(() => {
      this.dataThree = "three";
    }, 15000);
  }
}

<one [data]="dataOne"></one>
<two [data]="dataTwo"></two>
<three [data]="dataThree"></three>

export class OneComponent implements OnChanges {
  @Input() data: string;

  constructor(private spinner: NgxSpinnerService) {
    this.spinner.show();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes["data"] && changes["data"].currentValue) {
      this.spinner.hide();
      console.log(changes["data"].currentValue);
    }
  }
}

stackblitz

4 个答案:

答案 0 :(得分:1)

问题是ngxSpinnerService,因为它是单例服务。该文档的内容如下:

如果要多个ngx-spinner实例,只需在ngx-spinner组件中添加name属性。但是在这种情况下,您必须在show / hide方法中传递微调器的特定名称。

致谢

答案 1 :(得分:1)

在提供者列表中为每个子组件添加NgxSpinnerService

providers: [NgxSpinnerService]

答案 2 :(得分:0)

只需在每个组件实例中添加一个实例作为提供者,就像这样:

@Component({
  selector: "one",
  templateUrl: "./one.component.html",
  providers: [NgxSpinnerService] // <---- ADD THIS
})
export class OneComponent implements OnChanges {
  @Input() data: string;

  constructor(private spinner: NgxSpinnerService) {
    this.spinner.show();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes["data"] && changes["data"].currentValue) {
      this.spinner.hide();
      console.log(changes["data"].currentValue);
    }
  }
}

供参考:https://stackblitz.com/edit/angular-1hqv61

答案 3 :(得分:0)

一个非常简单的解决方案是添加计数器,每次更改时更新计数器,当计数器变为3时,这意味着所有3个子组件均已成功从父组件那里获得输入:-

Component({
  selector: "one",
  templateUrl: "./one.component.html",
  providers: [NgxSpinnerService] // <---- ADD THIS
})
export class OneComponent implements OnChanges {
  @Input() data: string;
dataChangeCounter =0;

  constructor(private spinner: NgxSpinnerService) {
    this.spinner.show();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes["data"] && changes["data"].currentValue) {
dataChangeCounter += 1;
if(dataChangeCounter ===3){
      this.spinner.hide();
}
    }
  }
}

这仅在只有一个输入属性的情况下才有效,不适用于多个输入属性,如果需要添加更多输入属性,则必须稍作更改。