0

My first attempt with Promise feature of angular. I'm trying to assign the value in the promise to a variable but i cannot get it to work. I want to use this final variable to populate the country data in 'select' dropdown.

console.log("1",this.globals.countryMasterDummy);
this.globals.countryMasterDummy.then(function(data){console.log("2",data)});
this.globals.countryMasterDummy.then(function(data: Countrymaster){ this.scanCountries = data}); 
console.log('3', this.scanCountries) ;  
this.globals.countryMasterDummy.then((data) => {   
  this.scanCountries = data;})
  .catch((ex) => {
      console.log(ex);});
console.log('4', this.scanCountries) ; 

this.scanCountries variable (which is declared as public scanCountries : Countrymaster), outside .then() is loosing value and hence unable to use this in populating dropdown.

Console msgs are enclosed: enter image description here

Updated Code:

this.globals.countryMasterDummy.then((data) => {   
  this.scanCountries = data;
  this.countryLoaded = true;
 // console.log('this.scanCountries',this.scanCountries);
})
  .catch((ex) => {
      console.log(ex);});

HTML:

 <div *ngIf="countryLoaded ; else loading; ">
            <span>Country</span> 
            <select class="form-control" [(ngModel)]="selectedOption">
              <option [ngValue]="null">ALL</option>            
              <option *ngFor="let scanCountry of scanCountries" [value]="scanCountry.alpha2_Country_Code"  >{{ scanCountry.Country_Name }}</option>
          </select>
          </div>
NewbieAngular
  • 51
  • 3
  • 11
  • A promise represents the result of an **asynchronous** process. It calls the callback you pass to then() **asynchronously**, i.e. later, when the result is available. So you can't expect the result to be available immediately after you've called then(). Just like, when you send an email, you can't expect the response to be available immediately after. That shouldn't prevent the dropdown to populate: it will populate when `this.scanCountries = data;`is executed, because Angular will detect the change. – JB Nizet Nov 25 '19 at 16:17
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – UncleDave Nov 25 '19 at 16:19
  • @ JB Nizet/@UncleDave--Thanks for the response, and understanding was easy with the example give, Reference link also helpful for the starters like me..,..Have done bit of addition in the code to take care of data availabilityin a later point....It works now...Thanks...Code updaed in the post. – NewbieAngular Nov 25 '19 at 16:55
  • Promises are a feature of JavaScript, not Angular. – Heretic Monkey Nov 25 '19 at 17:04

0 Answers0