4

I'm trying to retrieve data from DB and set it to the scope variable.'this' inside a callback not working as a angular2 scope. I don't know why. I tried timeout, zone. gas things, Promise things. I don't really know what they are, so I can't able to make use of it.

  //in service.ts
  listFriends(callback) {
    result_data = [];

    db.transaction(function(tx) {

        tx.executeSql('SELECT * from mytable', [], function(tx, results) {

            length = results.rows.length;

            for (i = 0; i < length; i++) {

                //console.log(results.rows.item(i));
                result_data.push(results.rows.item(i))
            }
            callback(result_data);

        }, null);

    });

}
//in component.ts
public allmyFriends: any;
public self = this;
public test;
constructor(myFriendService: MyFriendService) {



    this.myFriendService = myFriendService;
    this.myFriendService.listFriends((response) => {
        //trying to set value to the scope variable.but not working
        this.test="test working";
        //same as above
        this.allmyFriends = response;
        //getting the response from the service successfully
        console.log("in list" + this.allmyFriends);

    } );
  }
Nishanthd
  • 199
  • 2
  • 13

1 Answers1

5

When you said that you tried zone. What do you mean exactly? Do you inject NgZone and execute code within it.

This question could give you some hints: View is not updated on change in Angular2.

From where do you get your map instance. If it's instantiated outside a zone, Angular2 won't be able to detect updates of the mapLatitudeInput attribute.

You could try something like that:

export class MapComponent {
  constructor(ngZone:NgZone) {
    this.ngZone = ngZone;
  }

  someMethod() {
    this.myFriendService.listFriends((response) => {
      this.ngZone.run(() => {
        this.test="test working";
        this.allmyFriends = response;
        console.log("in list" + this.allmyFriends);
      });
    });
  }

This question could be also related to your problem: Angular2 child property change not firing update on bound property.

Hope it helps you, Thierry

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • OMG! NgZone. run () working like a charm. thank you so much @thierry. I have used this. _ngZone.runOutsideAngular () one, that's why it didn't work. do you know about it? – Nishanthd Jan 18 '16 at 08:59
  • 1
    Cool! Pleased to hear that ;-) The `runOutsideAngular` method is made to execute some processing outside Angular2, outside a zone that triggers the Angular2 change detection. So the behavior seems normal... – Thierry Templier Jan 18 '16 at 09:06
  • how can one test the code inside `run` function? i.e. make sure private variable is set? – umutesen Jul 27 '19 at 12:00