我无法从存储了服务数组的数组中找到元素。在控制台输出中,它始终显示未定义的消息

问题描述 投票:0回答:1

这是我的组件代码。在这段代码中,我将所有数据存储在本地数组中,以便从该数组中查找项目。但是,当我尝试从此数组中获取元素时,它显示为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)),   
                        ); 
                }
angular6 angular7
1个回答
0
投票

尝试在组件而不是构造函数中以新方法调用服务方法。

此方法应解决您的问题。

为什么?Angular: function calling on constructor

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

// ---------------------------------------------- ---------------Component.ts导出类AccountsComponent实现OnInit{retVal = [];构造函数公共服务: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//
            }
        }    //-------------------------------------------------------------   
© www.soinside.com 2019 - 2024. All rights reserved.