0

In Angular 5, I have observable array in service and I am subscribing this in component. And in the next line of statement I am checking whether the data was populated or not. But I found variable is not populated yet.

https://github.com/vsaravanan/ngx-mat-select-search.git

ERROR TypeError: Cannot read property 'slice' of undefined Error @ this.filteredBanksMulti.next(this.banks.slice());

I have a sample data running from jsonserver @ port 3000

        "banks"  :
        [
            { "name" : "apphugIndia", "id": "A"},
            { "name" : "batHugFr", "id": "B"},
            { "name" : "Bank C (France)", "id": "C"},
            { "name" : "hungary", "id": "D"},
            { "name" : "Hungary", "id": "E"},
            { "name" : "Bank F (Italy)", "id": "F"}
        ]

How to resolve this issue?

1 Answers1

1

if you are doing like this

this.httpCall.getData().subscribe(data=>this.recoreds = data);
this.records 

then its not going to work as , you call to server is still not complete you must need to wait for data to populate , that means you can do operation in subscribe method only.

to avoid issue you need to put you code in subscribe

this.httpCall.getData().subscribe(data=> {
      this.records = data;
      //do code here which uses  this.records
 });
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • ok. I can wait for data fetch to complete before the line "this.records". May I know to how to solve that? – singapore saravanan May 11 '18 at 07:31
  • you can, inside "subscribe" function, use a boolean variable "yetLoaded=true". (use this variable and *ngIf to show/hide a message "loading"). NOTE: in your code, I see that you're join service and component in the same file.ts -separate them an create two file.ts- and I see too that you're using the "old" and "deprecated" http, use httpClient instead of http – Eliseo May 11 '18 at 07:41
  • @singaporesaravanan - updated my answer please have look – Pranay Rana May 11 '18 at 08:05
  • I agree to the answers. But not sure how effectively I can put all the following statements within that subscribe function. Let me try. Thanks. – singapore saravanan May 11 '18 at 08:24