Angular service observable to return nested array data

混江龙づ霸主 提交于 2021-01-28 07:48:04

问题


My endpoint contains like this

{
        'dsco_st_license': {
            'ttco_st_license': [
                {
                    'csl_state': 'AK',
                    'csl_license_name': 'Specialty Contractor',
                    'csl_license_code': 'Communications',
                    'csl_license_number': '123456'
                },
                {
                    'csl_state': 'AL',
                    'csl_license_name': '',
                    'csl_license_code': '',
                    'csl_license_number': 'Not Required'
                }
            ]
        }
    }

and here is my service

ngOnInit() {
    this._WebLicenseServiceService.getWebLicensesHttpCall()
        .subscribe(data => this.weblicenses = data,
        err => console.error('Observer got an error: ' + err),
        () => console.log('close loading spinner')
    );

    console.log(this.weblicenses);
}

when i console.log(this.weblicenses); it dosnt contain the data. Instead looks like this

[]length: 0__proto__: Array(0)

I also tried

console.log(this.weblicenses['dsco_st_license']['dsco_st_license']);

But this errors out because of my interface

export interface IWeblicense {
csl_state: string;
csl_license_name: string;
csl_license_code: string;
csl_license_number: string;

}

How can I get the ttco_st_license to be returned?


回答1:


Access the response data inside subscribe function which ensure it will be executed once the response is completed.

ngOnInit() {
    this._WebLicenseServiceService.getWebLicensesHttpCall()
        .subscribe(data => {
           this.weblicenses = data;
           console.log(this.weblicenses); //<--- Get the data after call completes.
           console.log(this.weblicenses.dsco_st_license. ttco_st_license); //<---ttco_st_license
         },
        err => console.error('Observer got an error: ' + err),
        () => console.log('close loading spinner')
    );

    // console.log(this.weblicenses); //<-- Remove this since it will return undefined
}


来源:https://stackoverflow.com/questions/53344876/angular-service-observable-to-return-nested-array-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!