javascript - 获取有关组件负载的数据
问题描述
我有一个组件需要在组件/页面加载的网格中显示数据,当从父组件单击按钮时,它需要用新数据刷新网格。我的组件如下所示
export class TjlShipdateFilterComponent implements DoCheck {
tljShipDate: ShipDateFilterModel[];
constructor(private psService: ProjectShipmentService) {
}
ngDoCheck() {
// this data is from the service, trying to get it on Page load
}
@Input() filter: ShipDateFilterModel[];
//Load or refresh the data from parent when the button clicked from parent component
ngOnChanges(changes: SimpleChanges) {
}
ngOnChanges 工作正常,它从父组件获取数据并在从父组件单击按钮时显示。但是在加载页面/组件时,网格不显示任何内容并且说this.psService.tDate;
是未定义的。
以下是我得到的服务tDate
export class ProjectShipmentService {
......
constructor(service: DataService, private activatedRoute: ActivatedRoute) {
service.get<ShipDateFilterModel[]>(this.entityUrl).subscribe(x => this.tDate = x);
}
我不确定我在这里错过了什么。我怎样才能实现这种情况
解决方案
发生这种情况是因为当组件加载时,你的服务中的请求可能没有完成,数据可能还没有返回,这是为什么tDate
,undefined
尝试在你的组件中订阅它,也使用ngOnInit()
代替ngDoCheck()
。
在您的服务中:
tDate: Observable<ShipDateFilterModel[]>
constructor(service: DataService, private activatedRoute: ActivatedRoute) {
...
this.tDate = service.get<ShipDateFilterModel[]>(this.entityUrl)
}
在您的组件中:
export class TjlShipdateFilterComponent implements OnInit, OnChanges {
tljShipDate: ShipDateFilterModel[];
constructor(private psService: ProjectShipmentService) {
}
ngOnInit() {
// this data is from the service, trying to get it on Page load
this.psService.tDate.subsribe(x => this.tljShipDate = x);
}
@Input() filter: ShipDateFilterModel[];
//Load or refresh the data from parent when the button clicked from parent component
ngOnChanges(changes: SimpleChanges) {
if (changes.filter && changes.filter.currentValue)
{
this.tljShipDate = this.filter;
}
}
}
推荐阅读
- c# - 对列表求和,但仅适用于某个点之后的值
- html - 如何通过 GET http 参数传递对象
- python - cv2.inRange() 使其适用于所有输入
- python - 尽可能快地从 Base64 到 nparray,反之亦然
- flask - 是否可以从我的 Flask rest api 路由重定向到我的 Flask 应用程序中定义的不安 api
- d3.js - d3.json 在参数列表后得到“未捕获的语法错误:缺少)”
- mongodb - MongoError 的原因:Azure CosmosDB 上的连接超时
- java - Eclipse IDE 不能正确显示窗口标题
- python-3.x - Python过滤器字符串
- excel - 使用 VBA 将 Excel 文档中的所有行插入到另一个文档中