Angular 2类型脚本定义错误

时间:2017-12-07 07:45:33

标签: angular typescript syntax-error

将响应数据定义到数组时,发生错误:

public esriLocation = [];
public testLocation  = [];

 this.service.getData().subscribe(
                  (response) => this.esriLocation = response.json(),
                  (error) => console.log('ESRI ERROR: ' + error)
          );

          this.testLocation = this.esriLocation.suggestions;

财产'建议'不存在类型'任何'

性反应的

{
    "suggestions": [{
        "text": "DEU",
        "key": "dHA9MCNsb2M9MTAzOTkwNTEjbG5nPTQ0I2xicz0xMDk6NDI2MDI4NzM=",
        "isCollection": false
    }, {
        "text": "ENG",
        "key": "dHA9MCNsb2M9MTA0MDAzOTcjbG5nPTQ0I2xicz0xMDk6NDI2MDI4NzU=",
        "isCollection": false
    }]
}

如何解决?

2 个答案:

答案 0 :(得分:3)

尝试声明如下:

public esriLocation:any; 
public testLocation:any; 
    this.service.getData().subscribe(
                      (response) => {this.esriLocation = response.json()
                                     this.testLocation = this.esriLocation.suggestions;
                               },
                      (error) => console.log('ESRI ERROR: ' + error)
              );

答案 1 :(得分:2)

本质上是异步的,你需要在成功回调中进行分配。

public esriLocation = [];
public testLocation  = [];

 this.service.getData().subscribe(
                  (response) => {this.esriLocation = response.json()
                                 this.testLocation = this.esriLocation.suggestions;
                           },
                  (error) => console.log('ESRI ERROR: ' + error)
          );

因为它本质上是异步的,所以你不能保证结果在订阅块之后可用,如果它可用并且你发现它没有正确分配,请检查你是否得到一个JSON对象而不是字符串。