无法将服务中的数据订阅到组件

Unable to subscribe data from the Service to component

我正在尝试从服务中获取数据到下面的组件是我的服务

Service.ts

export class PrjService {
  tDate: Observable<filModel[]>;
  prjData:Observable<filModel[]>;
entityUrl;
constructor(){
this.entityUrl = 'PrjDetail/GetByRep';
    this.tDate = service.get<ShipDateFilterModel[]>(this.entityUrl);
}

我尝试检索的组件如下所示

export class RFComponent implements OnInit {
  cachedResults: any[];
  shipToData: any;

constructor(private psService: PrjService)
{}
  ngOnInit() {
     this.psService.tDate.subscribe(x => this.cachedResults = x);
     this.filterData = [...new Set(this.cachedResults.map(item => item.cus_name))].filter(Boolean);
  }

这里每当调用服务时 this.cachedResults 是未定义的,我在下面得到错误,就像我试图过滤的地方

ERROR TypeError: Cannot read property 'map' of undefined

不确定我在这里遗漏了什么

由于您正在进行异步调用,因此当控制到达 filteredData 语句时,cachedResults 值不会从服务中获取。这就是 undefined 错误的原因。

要解决该问题,您必须在服务调用完成并返回数据作为响应后执行语句

 ngOnInit() {
     this.psService.tDate
     .subscribe(x => {
        this.cachedResults = x;
        this.filterData = [...new Set(this.cachedResults.map(item => item.cus_name))].filter(Boolean);
     });
  }

另一种方法是使用 Observable 对象的 finally 方法。

 ngOnInit() {
        this.psService.tDate
        .finally(() => {
             this.filterData = [...new Set(this.cachedResults.map(item => item.cus_name))].filter(Boolean);
         })
        .subscribe(x => {
           this.cachedResults = x;
        });
    }

此处,finally 方法在可观察对象完成后或发生错误时调用。