类型'Promise <test []>'不能分配给类型Test [],'T Property'包含'缺少类型'Promise <test []>'

时间:2018-01-26 14:01:28

标签: angular angular5

test.component.ts:

export class TestcaseComponent implements OnInit {

  selectedDrpDown: Testcase[];

  //event handler for the select element's change event
  selectChangeHandler (event: any) {
    if(event.target.value == "ALL") {
      this.selectedDrpDown = this.getTest(); // error is coming here
    }
  }

}

data.service.ts:

// Get all Test
getTest(): Promise<Test[]> {
  return this.http.get(this.url)
           .toPromise()
           .then(response => response.json() as Test[])
           .catch(this.handleError);
 }

我需要在下拉列表的事件处理程序中返回selectedDrpDown,如何修复此转换错误。

1 个答案:

答案 0 :(得分:1)

从组件而不是服务中解包承诺。使用map函数将响应转换为json

getTest(): Promise<Test[]> {
return this.http.get(this.url)
           .toPromise()
           .catch(this.handleError);
}

selectedDrpDown: Test[];  
if(event.target.value == "ALL"){
           this.getTest()
           .then(response => {
                 this.selectedDrpDown = response as Test[]
            })
}