【问题标题】:The data returned from Angular2 RC3 http service is undefinedAngular2 RC3 http 服务返回的数据未定义
【发布时间】:2016-11-04 23:45:23
【问题描述】:

我设置了一个非常简单的网络项目来学习 Angular2 RC3 (TypeScript)。我目前没有后端,并尝试使用 HTTP GET 请求从 JSON 文件加载多个图像。

我遵循了有关创建服务的官方文档,并且一切运行都没有异常或错误。但是,尽管 HTTP GET 请求已成功完成并且我可以在 Firebug 中看到响应数据,但从我的服务返回的数据始终未定义。以下是我到目前为止所做的......

images.json 文件:

[
    {
      "description": "image1",
      "file": "image1.jpeg"
    },
    {
      "description": "image2",
      "file": "image2.jpeg"
    },
    {
      "description": "image3",
      "file": "image3.jpeg"
    }
]

负责加载 JSON 文件的服务部分如下所示:

import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
....
constructor(private http: Http) {}

getImages(imagesUrl) : Promise<Image[]> {
    return this.http.get(imagesUrl)
            .toPromise()
            .then(response => response.json().data)
            .catch(this.handleError);
};

Image 是一个简单的类:

export class Image {
    description : string;
    file : string;
}

使用该服务的组件部分如下所示:

...
@Component({
...
providers : [ ImageService ]
...
})
constructor(private imageService : ImageService) {}

ngOnInit() {
    this.imageService.getImages(this.imageSrcDir + "images.json")
        .then(images => console.log(images))
        .catch(error => console.log(error));
    }

console.log(images) 从上方显示 undefined

我对自己做错了什么感到很困惑,非常感谢任何帮助。

【问题讨论】:

    标签: angular


    【解决方案1】:

    缺少数据属性问题是“英雄之旅”Angular2 教程第 6 部分中的基本问题:https://angular.io/tutorial/toh-pt6 在将数据从静态模拟更改为使用 InMemoryDataService 时概述的步骤中。

    getHeros() 和 getHeros(id) 方法都有这个问题。删除表达式的“.d​​ata”部分将解析“未定义”结果。

    【讨论】:

      【解决方案2】:

      检查是否

      getImages(imagesUrl) : Promise<Image[]> {
          return this.http.get(imagesUrl)
                  .toPromise()
                  .then(response => response.json().data)
      };
      

      response.json() 中有任何内容。执行以下操作:

      .then(response => {
        console.log(response.json());
        return response.json().data)
      })
      

      【讨论】:

      • 也感谢安德烈的回复!我会记住调试。我用@JBNizet 的回答解决了我的问题。
      【解决方案3】:

      您的 JSON 结构是一个数组。您正在尝试访问该数组的 data 属性。但是数组没有任何data 属性。

      response.json() 是你的数组。无需附加.data

      【讨论】:

      • 不错@JBNizet!感谢您闪电般的快速回复。我完全错过了这个,现在它工作正常!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      相关资源
      最近更新 更多