【发布时间】: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