尝试使用服务在组件之间传递数据

Trying to pass the data between the component using the service

我正在使用服务在组件之间传递数据,我的组件如下所示

  constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) {

  }
  ngOnInit() {
    this.psService.getTDate().subscribe(x => this.cachedResults = x);
    this.populateArrays();

我的服务在哪里

 constructor(private service: DataService, private pInfo: ProjectDetailsComponent) {

    this.rProjectNumber = this.pInfo.rProjectNumber;
    this.rProjectSO = this.pInfo.rSalesOrder;
    this.entityUrl = this.pInfo.entityUrl;
    this.tDate = service.get<ShipDateFilterModel[]>(this.entityUrl);
   }

尽管在组件中订阅时 tDate 有数据但没有数据。 this.cachedResults 在 ngOnInIt 生命周期挂钩上调用服务时为空。我在这里错过了什么?

你为什么不简单地在服务中创建一个方法,比如

getTDate(){
return this.service.get<ShipDateFilterModel[]>(this.entityUrl);
}

并订阅你的组件

this.psService.getTDate().subscribe(x => this.cachedResults = x);

这样试试..

export class ProjectShipmentService {
  rProjectNumber;
  tDate: Observable<ShipDateFilterModel[]>;
  entityUrl;
  rProjectSO;

  constructor(private service: DataService, private pInfo: ProjectDetailsComponent) {
    this.rProjectNumber = this.pInfo.rProjectNumber;
    this.rProjectSO = this.pInfo.rSalesOrder;
    this.entityUrl = this.pInfo.entityUrl;
   }

getTDate(){
    return this.service.get<ShipDateFilterModel[]>(this.entityUrl);
}

在你的组件中。

  ngOnInit() {
    this.psService.getTDate.subscribe(x => this.cachedResults = x);
    this.populateArrays();
  }

希望这对您有所帮助:)