首页 > 解决方案 > Angular 6:从父组件接收数据后,在 ngAfterContentChecked 内连续执行 http 请求

问题描述

我是 Angular 的新手,我来自 React.js

我有一个问题,Angular在从父组件接收数据后HTTP永远在内部发出请求ngAfterContentChecked

我无法在里面提出请求,ngAfterContentInit因为我需要等待父母完成提出请求

我只希望它在从父级获取数据后立即调用一次

在 React.js 通常我会在里面发出请求componentWillReceiveProps

在 Angular 中,我会这样做。

父组件:

//codes...
groupId = '';
//codes...

ngOnInit() {
  const id = '23esaddq3sdasd';
  this.dataService.getUser(id).subscribe(data => {
    //codes...
    this.groupId = data.groupId;
    //codes...
  });
}

子组件:

data = [];
@Input() groupId;
fetch;

ngAfterContentChecked() {
  if (this.groupId) {
    const res = this.dataService.getGroupMembers(this.groupId).subscribe(data => 
      this.data = data;
      this.fetch = 'done';
    });
    if (this.fetch === 'done') {
      res.unsubscribe();
    }
  }
}

我尝试了unsubscribe它,但仍然不断地执行代码。

任何人,请帮助我

标签: javascriptangularreactjstypescript

解决方案


您可以使用 ngOnChanges() 代替 ngAfterContentChecked,当父使用 @input() 将数据传递给子组件时会触发它。

如果您有投影内容“ng-content”并访问父组件更改检测上的任何 DOM,则将使用 ngAfterContentChecked 生命周期。


推荐阅读