Search code examples
javascriptangulartypescriptangular7angular-routing

Unable to subscribe data from the Service to component


I am trying to get the data from the service in to the component below is my service

Service.ts

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

And the component where I try to retrieve is like below

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

Here whenever the Call to the service is made this.cachedResults is undefined and I get the error in the below like where I am trying to filter

ERROR TypeError: Cannot read property 'map' of undefined

Not sure what I am missing here


Solution

  • Since you are making an asynchronous call, by the time control reaches filteredData statement, cachedResults value isn't fetched from the service. That is the reason for the undefined error.

    To solve the problem, you have to execute the statement after the service call is completed and data is returned as response.

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

    Another approach would be to use the finally method of Observable object.

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

    Here, the finally method is called after the observable completes or when error occurs.