首页 > 解决方案 > 获取有关组件负载的数据

问题描述

我有一个组件需要在组件/页面加载的网格中显示数据,当从父组件单击按钮时,它需要用新数据刷新网格。我的组件如下所示

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);
   }

我不确定我在这里错过了什么。我怎样才能实现这种情况

标签: javascriptangulartypescriptangular7

解决方案


发生这种情况是因为当组件加载时,你的服务中的请求可能没有完成,数据可能还没有返回,这是为什么tDateundefined尝试在你的组件中订阅它,也使用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;
  }
 }
}

推荐阅读