Angular 2等待服务结果到来

标签 angular typescript

有一个简单的搜索表单。我尝试做的是:

  • 在输入字段中输入一个数字
  • 点击搜索按钮
  • 服务找到该项目并将其返回到表单

这有效,但前提是我单击搜索按钮两次。问题是,当我尝试处理该服务时,我认为所建立的数据尚 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/

相关文章:

javascript - 如何在 typescript 中指示对象可能没有键

javascript - 使用 onClick 和 TypeScript 响应功能 <a> 组件

javascript - 以编程方式为我的环境中的环境键声明 typescript 类型

javascript - 为什么 typescript 看不到我的功能?

javascript - typescript 无法导入没有扩展名的文件

angular - 如何在 Angular 2 中迭代 JSON 对象?

angular - 如何使用 AngularFire 从 FireBase 存储获取文件列表

node.js - NestJS 和 TypeORM 问题有或没有 tsconfig 目标 es5

angular - 在 angular 2 Component 中使用 setInterval 函数

typescript + Angular2 : Subscribing to Observable causes "Unrecognized teardown 1" error