isADon
isADon

Reputation: 3673

TypeScript Store Parse Query result

I have following code

export class AppComponent implements OnInit {
  public guests: any[] = [];


  constructor(private apiService: ApiService) {

  }

  ngOnInit(): void {
    this.apiService.getAllGuestsQuery().find({
      success(results) {
        for (let i = 0; i < results.length; i++) {
          const object = results[i];
          console.log(object.get('companyName'));
        }
      },
      error(error) {
        console.log("Error: " + error.code + " " + error.message);
      }
    });
  }
}

The getAllGuestsQuery returns a Parse.Query object. I would like to store the result in my guests array. E.g. do something like this.quests = results But I cannot access this.guests class variable inside the success method.

How can I do that?

Upvotes: 1

Views: 539

Answers (2)

vfioox
vfioox

Reputation: 738

export class AppComponent implements OnInit {
  public guests: any[] = [];


  constructor(private apiService: ApiService) {

  }

  ngOnInit(): void {
    let vm = this;
    this.apiService.getAllGuestsQuery().find({
        func(r){ vm.guests } // will be available
    });
  }
}

This is caused because when you pass the {} construct to the find() function a new scope is being created there. If you used the ES6 arrow syntax you could make this better(but a hassle for me to write, you'd have to handle the errors in a totally different manner, preferably promises)

Upvotes: 1

Greg
Greg

Reputation: 1931

You could try passing a reference to this in a separate variable at the beginning of your ngOnInit() method. Something like let that = this;. Refer to this (class instance) via that later on in your callback.

Upvotes: 0

Related Questions