问题
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