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

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


服务.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是未定义的,我在下面收到错误,就像我试图过滤的地方


错误类型错误:无法读取未定义的属性“地图”


不确定我在这里缺少什么


沧海一幻觉
浏览 132回答 1
1回答

呼如林

由于您正在进行异步调用,因此在控制到达filteredData语句时,cachedResults不会从服务中获取值。这就是undefined错误的原因。要解决该问题,您必须在服务调用完成并返回数据作为响应后执行该语句。&nbsp;ngOnInit() {&nbsp; &nbsp; &nbsp;this.psService.tDate&nbsp; &nbsp; &nbsp;.subscribe(x => {&nbsp; &nbsp; &nbsp; &nbsp; this.cachedResults = x;&nbsp; &nbsp; &nbsp; &nbsp; this.filterData = [...new Set(this.cachedResults.map(item => item.cus_name))].filter(Boolean);&nbsp; &nbsp; &nbsp;});&nbsp; }另一种方法是使用finallyObservable 对象的方法。&nbsp;ngOnInit() {&nbsp; &nbsp; &nbsp; &nbsp; this.psService.tDate&nbsp; &nbsp; &nbsp; &nbsp; .finally(() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.filterData = [...new Set(this.cachedResults.map(item => item.cus_name))].filter(Boolean);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; &nbsp; &nbsp; .subscribe(x => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.cachedResults = x;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }在这里,该finally方法在 observable 完成后或发生错误时调用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript