0

I have piece of code, which is not working, and I couldn't manage why. Help please.

@Injectable()
export class PersonService {
    private person: Person = new Person();
    ...
    getPerson(name: string): void {
        const url = `${this.personsUrl}/getByName/${name}`;
        this.http.get<Person>(url).toPromise().then(r => {
            console.log(r);  // {id: 1, name: "PersonName"}
            console.log(r.name);  // PersonName
            console.log(r.id);  // 1
            this.person.id = r.id;
            this.person.name = r.name;
        });
        console.log(this.person) // Person {} <--- why?
    }
}

I have tried to create a Person object inside then() function, return it, return Promise etc. Tried making copy of documentation, but still it doesn't work for some reason.

Vitali
  • 549
  • 6
  • 16

1 Answers1

0

Classic async vs sync issue - you're logging the result before the update has happened. Try appending another then and logging out person, or alternatively (assuming your using a modern version of Node) use async / await e.g.

async getPerson(name: string): void {
  ...
  const result = await this.http.get<Person>(url).toPromise();
  // update this.person
}
James
  • 80,725
  • 18
  • 167
  • 237