I have a problem when im trying to assign return value from service to 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');
});
}
It successfuly got returned value in console.log
inside the subscribe()
. there are seems like no problem. even i set the console.log to variable inside the subscribe()
:
.subscribe(data => {
this.inspectionResult = data;
console.log(`value from getInspectionData: `, this.inspectionResult);
it had give the this.inspectionResult
output correctly.
it should be correct, right? and then i add this.inspectionResult = data;
but....
when i test it, the variable gets wrong and it gets '{}'
. the code below:
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');
});
}
by the way, i had assigned the variable like this:
inspectionResult: InspectionResult = <InspectionResult>{};
inspectionResultData: InspectionResultData = <InspectionResultData>{};
my question is:
this.inspectionResult
?console.log()
in ngOnInit()
should run after the getInspectionData();
)that may due to
this.getInspectionData();
console.log(value from getInspectionData:
, this.inspectionResult);
in this case there may delay in this.getInspectionData() this process. but console.log() is exicuting before the above method complete.
you must await for method complete. please refere this you will get some clarity
http://www.damirscorner.com/blog/posts/20170127-Angular2TutorialWithAsyncAndAwait.html