1

I am new to using Angular 2 (and front end development in general), and I've hit a problem regarding variable scope. I cannot tell if this is because of some knowledge gap I have with Angular 2 (and zones) or if I am missing something else entirely.

sqlEngine;

constructor(private zone: NgZone) {
  this.sqlEngine = new cartodb.SQL({user: 'user', format: 'geojson'});
}

cartoDBSQLEngine(SQLquery: string, SQLuser: string, returnFormat: string, propertyType: string){
  var returnthis;
  var test = 50;
  this.sqlEngine.execute(SQLquery).done(function (geojson){
    for (var i = 0; i < geojson.features.length; i++){
      geojson.features[i].properties.type = propertyType;
    }
    console.log("Direct GeoJSON output below:");
    console.log(geojson);
    returnthis = geojson; 
    console.log(returnthis); //here returnthis is equal to geojson.
    console.log("Test: "+test); //this returns 50.
    test = 20;
  });
  console.log("Test2: "+test); //this remains 50.
  return returnthis; //here returnthis is undefined.
}

I cannot tell if this is a scope issue or an asynchronous issue - am I trying to make 'returnthis' equal to something that may not have been initialised yet? How do I access the data from 'geojson' from within the callback function, outside of the callback function?

In the constructor I have 'NgZone', as some other posts were mentioning Angular 2 zones with Asynchronous functions requiring NgZone to run outside of the Angular 2 environment. I don't really understand that - nor how to use NgZone to access the variable.

UPDATE: Working code:

cartoDBSQLEngine(SQLquery: string, SQLuser: string, returnFormat: string, propertyType: string){
    this.sqlEngine.execute(SQLquery).done((geojson) => {
      for (var i = 0; i < geojson.features.length; i++){
        geojson.features[i].properties.type = propertyType;
      }
      this.addDatatoMap(geojson);
    });
  }

Turns out I had two issues to solve. I needed to fix the scope issue using '=>' to allow the 'done' function to access parent variables. I then needed to fix the asynchronous issue, so I called the function within the 'done' callback.

dandev91
  • 1,691
  • 3
  • 22
  • 34
  • *"I cannot tell if this is a scope issue or an asynchronous issue"* Yep, it's an asynchronous issue. The callback is executed *after* the function returned. – Felix Kling Oct 06 '16 at 04:28
  • Thanks Felix Kling - I didn't realise this was simply an 'asynchronous' issue. I appreciate the assistance! – dandev91 Oct 06 '16 at 04:36

0 Answers0