0

Here is my component code. In this code I have stored all data in a local array to find an item from this array. But when I try to get an element from this array it shows undefined.

   //-------------------------------------------------------------           
    Component.ts
            export class AccountsComponent implements OnInit
            {
                retVal = [];
                constructor(
                public service:AccountingService) 
                { 
                    this.service.getAccounts().forEach(item=>{
                    this.retVal.push(item['chartofaccount']); // Locally stored the value to an array//
                    });      
                }

                ngOnInit() 
                {
                    console.log(this.getAccountById(2));
                }
                getAccountById(id)
                {
                    return this.retVal.find(x => x.id === id);  // Return value showed undefined//
                }
            }    //-------------------------------------------------------------   
            Service.ts
             getAccounts():Observable<ChartOfAccount[]>
                {
                    return this._htc.get<ChartOfAccount[]>(this.apiUrl+'chart-of-account', httpOptions)
                    .pipe(
                        tap(data => console.log("Data:", data)),   
                        ); 
                }
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0

Try to call your service methods in new method in your component instead of constructor.

This approach should fix your problem.

Why? Angular: function calling on constructor

https://www.angularjswiki.com/angular/what-is-the-difference-between-constructor-and-ngoninit-in-angular/

//-------------------------------------------------------------
Component.ts export class AccountsComponent implements OnInit { retVal = []; constructor( public service:AccountingService) {

                });      
            }

            ngOnInit() 
            {   this.getAccountsData();
                console.log(this.getAccountById(2));
            }
            getAccountsData() {
                this.service.getAccounts().forEach(item=>{
                this.retVal.push(item['chartofaccount']); // Locally stored the value to an array//
                }); 
            }
            getAccountById(id)
            {
                return this.retVal.find(x => x.id === id);  // Return value showed undefined//
            }
        }    //-------------------------------------------------------------   
pradeepks
  • 53
  • 1
  • 6