I have some TS code that checks the nearest point around you for car assistance (determined by a database), and after having establishhed that he takes its phone number and calls it. Problem: it only works after the first click that triggers the event, first attempt returning undefined as a result.
repairerInfoCall: RepairerInfo;
userLongitude: number;
userLatitude: number;
repairersHeaderInfo: RepairerHeaderInfo[]; /established onInit/
navigateToComponent(navigationButton: NavigationButtonsEnum) {
switch (navigationButton) {
/.../
case NavigationButtonsEnum.RoadsideAssistance:
/.../
else if (this.userLatitude != null && this.userLongitude != null && this.repairersHeaderInfo != null) {
let data = this.repairersHeaderInfo.reduce((prev, current) => (prev.distance < current.distance) ? prev : current);
this.repairerService.getCompanyInfoById(data.id.toString()).subscribe(repInfo =>{
this.repairerInfoCall = repInfo
})
window.location.href = "tel:" + this.repairerInfoCall.phoneNumber;
}
/.../
HTML:
<button mat-raised-button class="home-buttons"
(click)="navigateToComponent(navigationButtonsEnum.RoadsideAssistance)">
<img src="assets/icons/tow-truck.png" class="home-icons">
<div>Soccorso stradale</div>
</button>
</div>
The code works and it rightly gets all the info needed (from server). The only issue is that the first time it tries to subscribe it doesn't, meanwhile the second time and later it works pefectly. Why is that?
The Problem here is that the local repairerInfoCall won't be updated before calling window.location.href = "tel:" + this.repairerInfoCall.phoneNumber;
Observables extends Promises, they are asynchronous.
You could do following:
async navigateToComponent(navigationButton: NavigationButtonsEnum) {
/.../
this.repairerInfoCall = await this.repairerService.getCompanyInfoById(data.id.toString()).toPromise();
window.location.href = "tel:" + this.repairerInfoCall.phoneNumber;
/.../