有一个简单的搜索表单。我尝试做的是:
- 在输入字段中输入一个数字
- 点击搜索按钮
- 服务找到该项目并将其返回到表单
这有效,但前提是我单击搜索按钮两次。问题是,当我尝试处理该服务时,我认为所建立的数据尚 future 自该服务。
应用程序
@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];
});
}
如何先加载对象(数据)然后开始处理它?</p>
最佳答案
您必须在 then
调用中使用更详细的表示法:
onSearch(nummer) {
this.myService.getByNummer(nummer).then((i: Instelling) => {
this.selectedInstelling = i;
//do whatever you want in here...
});
}
关于Angular 2等待服务结果到来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361206/