从Angular2 RC3 http服务返回的数据未定义 [英] The data returned from Angular2 RC3 http service is undefined

查看:59
本文介绍了从Angular2 RC3 http服务返回的数据未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个非常简单的Web项目来学习Angular2 RC3(TypeScript).我目前没有后端,请尝试通过HTTP GET请求从JSON文件加载多个图像.

I have setup a quite simple web project to learn Angular2 RC3 (TypeScript). I do not have a backend at the moment and try to load several images from a JSON file with an HTTP GET request.

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

I have followed the official documentation on creating services and everything runs without exceptions or errors. However, the data returned from my service is always undefined despite that the HTTP GET request is completed successfully and I can see the response data in Firebug. Following is what I have done so far...

images.json 文件:

images.json file:

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

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

The part of the service responsible for loading the JSON file looks like this:

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);
};

图像是一个简单的类:

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

使用该服务的组件的部分外观如下:

The component that uses the service looks in part like this:

...
@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)显示未定义

我对自己做错了事感到很困惑,真的很感谢任何帮助.

I am quite puzzled as to what I did wrong, any help is really appreciated.

推荐答案

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

Your JSON structure is an array. You're trying to acces the data attribute of that array. But arrays don't have any data attributes.

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

response.json() is your array. No need to append .data.

这篇关于从Angular2 RC3 http服务返回的数据未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆