0

I'm entirely new to modern JavaScript. I'm trying to populate an array with data I get from a promise from a helperService.

export class PeopleTableComponent implements OnInit {
    people: Array < Person > = [];

    constructor(public helperService: HelperService) {}

    ngOnInit(): void { 
        this.helperService.getPeople().then(res => {
            res["people"].forEach(function(person) {
                let person = new Person();
                person.name = person.name;
                this.people.push(person);
            });
        });
    }
}

class Person {
    name: string;
}

However this.people.push(person); doesn't work since this is undefined (as I verified in debugging).

In other frameworks, I used to solve this with .bind(this). Maybe this would work here but is it the correct way? What is the recommended way to pass the context inside the promise callback?

Saturnix
  • 10,130
  • 17
  • 64
  • 120

1 Answers1

1

Using arrow functions would fix that.

Plus you don't really need to instantiate a new Person Object, every single time. In Angular, we generally use interfaces for static type checking. So unless you have a very strong reason to use classes instead, just use interfaces.

Keeping all that in mind your code can be refactored to:

export class PeopleTableComponent implements OnInit {
  people: Array < Person > = [];

  constructor(public helperService: HelperService) {}

  ngOnInit(): void {
    this.helperService.getPeople().then(res => this.people = res.people);
  }
}

interface Person {
  name: string;
}
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • Precisely the kind of modern best-practice guide I've needed, thank you! The automatic creation of the array of Person instances in just one line is insane! – Saturnix Jul 31 '19 at 15:57