Angular 5:无法从HttpClient get请求获得响应

时间:2018-03-13 01:27:25

标签: angular typescript compiler-errors angular5

好的,所以我主要是一个Angular 1. *开发者,我想我会试试角度5,到目前为止,我必须说它给了我地狱。比任何方式都要复杂的方式但无论如何......

所以我进行了一次HTTP调用,我有这个返回的节点API 像这样:

apiRoutes.route('/api/code').get(function (req, res) {
...
res.json({status: 200, code: FOO})
});

同时在Angular 5中:

 this.http.get(WEB_CONFIG.API_DOMAIN + 'api/code').subscribe(res => {
            console.log(res) //<----- no error
            console.log(res.code) //<---- Property 'code' does not exist on type 'Object' (WTF)
          });

为什么我无法访问res的任何属性(至少在编译时根据VS Code)???如果我省略第二个日志并运行应用程序,我可以在控制台中看到'res'json ...

2 个答案:

答案 0 :(得分:2)

打字退货是一种很好的做法,但你也没有。您可以使用any

this.http.get(WEB_CONFIG.API_DOMAIN + 'api/code').subscribe((res : any) => {
        console.log(res.code) 
      });

答案 1 :(得分:0)

好的,我将回答我自己的问题。显然,由于类型检查或任何你想要调用它,我需要先:

1。)定义我的api接口。使用角度CLI我做了:ng g interface apiConfig

2。)配置它以确保属性与API端点返回的属性相匹配:

export interface ApiConfig {
status: Number,
code: String
}

3.。)在我的组件中包含接口:

import { ApiConfig } from '../api-config';

4.)然后在我的'HTTPClient'请求中使用此语法:

gCode: ApiConfig

//......... Other stuff........//

this.http.get<ApiConfig>(WEB_CONFIG.API_DOMAIN + 'api/code')
    .subscribe(data => {
      this.gCode = {
        ...data //<----- Yes this weird ellipsis syntax is actually correct
      };
});

我想我只是不习惯所有这种类型的javascript ....