I have a lack of understanding asynchronous operation while I'm dealing with a promise function in angular. So basically, I'm trying to get a value from a promise method and assign it to a global variable in a component. However, I am unable to retrieve the value when I click on a button once and it finally starts to show the value after I clicked on a button once more.
Error I get when I clicked it once:
Cannot read property 'matchId' of undefined
Value I get after I clicked it twice:
3
Html:
<button type="submit" (click)="loadInfo(form)">Submit</button>
Service:
@Injectable()
export class Web3Service {
constructor...
getInfo(address: string): Promise<any> {
return this.TestBetting.deployed().then((instance) => {
return instance.getInfo.call(address);
})
.then((value) => {
var serialized = this.itemsService.getSerialized<IGetInfo>(value);
return this.mappingService.mapValueToGetInfo(serialized);
})
.catch((e) => {
console.log(e);
});
}
}
Component:
export class HomeComponent {
infoMapped: any;
constructor(private web3Service: Web3Service) {}
loadInfo(): void {
var test = this.web3Service.getInfo(this.address);
test.then((value) => {
this.infoMapped = value;
})
// this.infoMapped.matchId is undefined on a first attempt
var length = this.infoMapped.matchId;
for (var i = 0; i < length; i++) {
//...
}
}
}
What needs to be fixed so that infoMapped
value can be retrieved after clicking a button only once?
The problem is still that code after the
test.then()
(i.e. thefor
) will execute before thethis.infoMapped = value;
becausethis.infoMapped = value;
will only execute when thetest
promise resolves, and it will only resolve some time after thefor
runs.What I suggest: move the "handling" logic to a new method and call it from the
.then()
.So, this:
Would become this: