2016-12-28 34 views
2

A有一个简单的搜索表单。我尝试做的是:Angular 2等到服务结果出来

  • 给出nummer到输入字段
  • 搜索按钮
  • 点击
  • 服务找到该项目,并使其返回到窗体

这工作,但只有当我点击搜索按钮两次。问题是我认为,当我尝试着解决这个问题时,创建的数据还没有来自服务。

应用

@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...... } 
} 

服务

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]; 
     }); 

} 

我怎样才能加载对象(数据)第一然后开始进行这项工作?

+1

谷歌关于JavaScript的承诺和角2执行情况相同。这就是你的解决方案所在。 –

回答

2

您必须使用更复杂的符号在then电话:

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