Korki Korkig
Korki Korkig

Reputation: 2814

Angular 2 wait until service result comes

A have a simple search form. What I try to do is:

This works but only if I click twice on the Search Button. The problem is I think that the founded data doesn't come yet from the service when I try to work on it.

App

@Component({
    template: `
    <input pInputText #inputNr"/>
    <button pButton type="button" (click)="onSearch(inputNr.value)"></button>
            `
})

constructor(private myService: MyService) { }

ngOnInit() {
    this.selectedInstelling = new Instelling();
}

onSearch(nummer) {

    this.myService.getByNummer(nummer)
                              .then(i => this.selectedInstelling = i);

    ......... // I want to do some work here when I get the data

    console.log(this.selectedInstelling); // First Click:  Object { vorms: Array[0] }
                                          // Second Click: Object { id: 1, naam: "Provincia...... }
}

Service

getByNummer(nummer: string) {

    return this.http.get('my json file')
        .toPromise()
        .then(res => <Instelling[]> res.json().filter(i => i.inummer === nummer))
        .then(data => {
            return data[0];
        });

}

How can I load the object(data) first then start to work on it?

Upvotes: 2

Views: 2098

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71961

You have to use the more elaborate notation in the then call:

onSearch(nummer) {
    this.myService.getByNummer(nummer).then((i: Instelling) => {
       this.selectedInstelling = i;
       //do whatever you want in here...
    });
}

Upvotes: 2

Related Questions