【发布时间】:2017-07-25 07:00:32
【问题描述】:
我正在从服务中获取 json 对象,我想迭代到这个 json 对象并填充类类型的数组。 以下是调用服务的代码
public GetMapData(): Observable<Response> {
var path = 'http://my.blog.net/blog.php?type=trendingDestiny';
return this.http.get(path)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
self.blogapi.GetMapData().subscribe(
x => {
this.MapData = x;
console.log("MapData", this.MapData);
});
下面是json响应
[
{
"post_id": 77,
"post_title": "Delhi",
"post_content": "DelhiDelhiDelhi",
"post_date": "2017-07-24 11:47:08",
"imageurl": false,
"cat_name": [
{
"term_id": 7,
"name": "FOODIE",
"slug": "foodie",
"category_parent": 0
}
],
"longitude": "75.857849",
"latitude": "33.888586",
"region_name": "Asia"
},
{
"post_id": 75,
"post_title": "Goa",
"post_content": "this is goa",
"post_date": "2017-07-24 11:03:59",
"imageurl": false,
"cat_name": [
{
"term_id": 7,
"name": "FOODIE",
"slug": "foodie",
"category_parent": 0
}
],
"longitude": "75.857849",
"latitude": "33.888586",
"region_name": "Asia"
}]
以下是打字稿代码
this.MapData.forEach(map => {
this.Mapdatalist.push({
postid: map.post_id,
regionname: map.region_name,
longitude: map.longitude
});
});
或者我也试过
for (let data of this.MapData)
{
console.log("error",data);
}
但是没有任何效果。它给了我错误
错误类型错误:无法读取未定义的属性“forEach”
请帮忙看看出了什么问题。
【问题讨论】:
-
this.MapData未定义。 -
你是如何从服务中获取这个 json 对象的?这段代码是什么样的?
-
@Shubham this.mapdata 有数据,当我在 html 中使用 ngfor 时它可以工作。
-
this.mapdata 还是 this.MapData ?
-
@C.jacking 尝试在控制台中记录
this.MapData并检查你得到了什么。
标签: javascript arrays json angular