【问题标题】:Get data on the Component load获取组件负载数据
【发布时间】:2019-12-31 04:17:18
【问题描述】:

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

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

我不确定我在这里缺少什么。我怎样才能实现这种情况

【问题讨论】:

  • 如果this.psService.tDateundefined,你能把赋值给tDate的代码加上,它是什么时候赋值的?
  • @EthanVu 我更新了代码以显示我获得 tDate 的服务

标签: javascript angular typescript angular7


【解决方案1】:

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

【讨论】:

  • 服务中的tDateservice 是什么
  • 已更新,它将分配给tDate的请求
【解决方案2】:

这里有几个选项。 NgOnInit 将在创建组件时运行,在渲染之前。这是在组件初始化时加载数据的最常用方法。 如果您甚至在组件初始化之前就需要数据,那么您可能需要使用解析器。 这是一个例子:

import { Injectable } from '@angular/core'
import { HttpService } from 'services/http.service'
import { Resolve } from '@angular/router'
import { ActivatedRouteSnapshot } from '@angular/router'

@Injectable()
export class DataResolver implements Resolve<any> { 
    constructor(private http: HttpService) { }
    resolve(route: ActivatedRouteSnapshot) {
        return this.http.getData(route.params.id);
    }
}

然后,在您的路线配置中:

{
    path: 'data/:id',
    component: DataComponent,
    resolve: { data: DataResolver }
}

ActivatedRouteSnapshot 的包含是可选的,只有在使用路由数据(如参数)时才需要它。

编辑: 仔细观察您的示例,ngDoCheck 是否可能在 psService 订阅之前触发?

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 2016-10-05
    相关资源
    最近更新 更多