javascript - 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
它,但仍然不断地执行代码。
任何人,请帮助我
解决方案
您可以使用 ngOnChanges() 代替 ngAfterContentChecked,当父使用 @input() 将数据传递给子组件时会触发它。
如果您有投影内容“ng-content”并访问父组件更改检测上的任何 DOM,则将使用 ngAfterContentChecked 生命周期。
推荐阅读
- paypal - 替代未弃用的计费协议?
- angular - 登录页面在浏览器中不起作用,但该方法适用于 Postman
- elasticsearch - Elastic Search 中 doc.field_name 与 field_name 之间的区别?
- git - Git 无法获取远程分支
- react-native - 如何在本机反应中打开“将图像设置为”意图?
- docker - Kubernetes 没有提取最新的镜像
- android - Kotlin Android 工作室充气机崩溃问题
- node.js - 如何处理nodejs中的br和gz文件?
- json - 使用带有映射的 LowDB 访问嵌套的 Json 值
- java - 使用 WebMvcTest 测试具有重复名称的控制器