I encountered an issue while trying to assign the return value from a service to a component.
ngOnInit() {
this.getInspectionData();
}
getInspectionData() {
this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`)
.subscribe(data => {
console.log(`this is data returned: `, data);
}, error => {
console.log('failed to get data', error);
}, () => {
console.log('getInspectionResult successfully processed');
});
}
The return value was successfully captured in the console.log output.
Within the subscribe()
function, everything appears to be functioning correctly. I even assigned the value to a variable inside the subscribe()
:
.subscribe(data => {
this.inspectionResult = data;
console.log(`value from getInspectionData: `, this.inspectionResult);
The output of this.inspectionResult
was correct.
So, it seemed like everything was in order. However, when I tested it, the variable ended up with an unexpected value of '{}'
. Here is the code snippet:
ngOnInit() {
this.getInspectionData();
console.log(`value from getInspectionData: `, this.inspectionResult);
}
getInspectionData() {
this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`)
.subscribe(data => {
this.inspectionResult = data;
}, error => {
console.log('failed to get data', error);
}, () => {
console.log('getInspectionResult successfully processed');
});
}
Additionally, I had initialized the variables as follows:
inspectionResult: InspectionResult = <InspectionResult>{};
inspectionResultData: InspectionResultData = <InspectionResultData>{};
My questions are:
- Why is the data value not being assigned to
this.inspectionResult
? - Why is the
ngOnInit()
not producing the expected output? (Theconsole.log()
withinngOnInit()
should run aftergetInspectionData();
)