【问题标题】:Angular2 HTTP TypeScript JsonAngular2 HTTP TypeScript Json
【发布时间】:2017-02-27 12:06:48
【问题描述】:

我有一个本地存储的“region.json”文件,如下所示:

{
  "regionId":1, 
  "region":"CAN"
},
{
  "regionId":2, 
  "region":"CEN"
}

我有这样的“环境-app.component.ts”文件:

import {Component, View, CORE_DIRECTIVES, FORM_DIRECTIVES} from "angular2/core";
import {HTTPTestService} from "./http-test.service";

@Component({
   selector: 'my-app'
})

@View({
  template: `

<table>
    <thead>
        <th>Region Id</th>
        <th>Region</th>
    </thead>
    <tbody>
        <tr *ngFor="#item of myData">
            <td>{{item.regionId}}</td>
            <td>{{item.Region}}</td>
        </tr>
    </tbody>
</table>`
  })
export class AppComponent {
myData:any;
}

我有“http-test.service.ts”文件,看起来像:

import {Injectable} from "angular2/core";
import {Http} from "angular2/http";
import 'rxjs/add/operator/map';
import {Headers} from "angular2/http";
import {AppComponent} from "./environment_app.component";

@Injectable()
export class HTTPTestService{
constructor (private _http: Http){}

this.myData = {region:[]};
get("./region.json") {
   return this._http.get("./region.json", { headers: headers })
        .map(res => res.json())
        .subscribe
         (
         data => {
            this.myData = data;
         });
}
}

在前端,我只能将标题打印为

我想获取所有的 json 数据

我做错了什么?? 请,任何帮助表示赞赏,

提前致谢。

【问题讨论】:

  • 您的路径需要与您的组件所在的应用文件夹相关联app/data/region.json
  • @MaciejCaputa 我尝试了您在评论中所说的,但仍然无法正常工作,仍然打印了标题。
  • 忽略我之前的评论,无论出于何种原因,我认为您有获取错误(您可以在控制台中仔细检查)。您正在运行什么角度版本?如果它是最终版本,那么 ngFor 的语义已经改变,必须使用 *ngFor=`let item of myData' 代替。您使用的语法在 Angular 2.x-beta 中使用过。
  • 是的,您正在使用已弃用的角度。 @View 也被弃用了。

标签: json typescript angular2-http


【解决方案1】:

json 的响应进入名为 myData 的变量中。此变量是服务的成员,而不是您的 AppComponent 类。不过,

*ngFor="#item of myData"

在上面的 *ngFor 中,这个 myData 变量是你的 AppComponent 类的一部分,它从未被填充。

这样做:

  1. 创建一个函数,就像您在服务中所做的那样,在读取文件后返回 json 数据。
  2. 将该数据返回给 AppComponent。
  3. 将其分配给 AppComponent 中的 myData。

【讨论】:

    猜你喜欢
    • 2017-09-09
    • 2016-10-25
    • 2016-06-13
    • 2016-07-28
    • 2016-06-12
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多