2

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

  • give an nummer into the input field
  • click on search button
  • service finds the item and returns it back to the form

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?

1
  • 1
    Google about JavaScript Promise and Angular 2 Implementation for the same. That's where your solution lies. Commented Dec 28, 2016 at 11:33

1 Answer 1

2

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...
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.