获取有关组件加载的数据 [英] Get data on the Component load
问题描述
我有一个需要在组件/页面上的网格中显示数据的组件,当从父组件中单击按钮时,它需要使用新数据刷新网格.我的组件如下
I have a component which needs to show the data in the grid on the component/page Load and when a button is clicked from parent component it needs refresh the grid with new data. My component is like below
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;
未定义.
The ngOnChanges works fine, it gets the data from the parent component and displays when the button is clicked from the parent component. But on load of the page/component the grid it doesn't show anything and says this.psService.tDate;
is undefined.
下面是我获得tDate
export class ProjectShipmentService {
......
constructor(service: DataService, private activatedRoute: ActivatedRoute) {
service.get<ShipDateFilterModel[]>(this.entityUrl).subscribe(x => this.tDate = x);
}
我不确定我在这里想念什么.我该如何实现这种情况
I am unsure what am I missing here. How can I achieve this scenario
推荐答案
发生这种情况是因为在加载组件时,服务中的请求可能未完成,数据可能尚未返回,因此tDate
是ngOnInit()
而不是ngDoCheck()
.
It happened because when the component is loaded, the request in your service may not completed and the data may not return yet, that why tDate
is undefined
, try subscribe to it inside your component, also use ngOnInit()
instead of 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;
}
}
}
这篇关于获取有关组件加载的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!