在typescript中加载JSON文件的最佳方法是什么?

时间:2016-06-03 13:09:38

标签: jquery json typescript angular

我想在用typescript编写的angular2 app中加载一个本地JSON文件用于测试目的。我有1)包含jQuery.d.ts文件,并尝试使用$ .getJson()2)尝试$ .ajax()与async:false。这两个问题都是我无法调用回调函数之外的函数。

ngOnInit():any {
    $(document).ready(function(){
        $.ajax({
            async: false,
            url: "../jsonfile/guestRecommendations/1.json",
            dataType: "json",
            method: "GET",
            success: function (data) {
                this.hello();
            }
        });
        alert(this.json_data);
    })
    this.json_data = "before";
}

 hello(){
    alert("hello");
}

}

抛出此错误EXCEPTION:TypeError:this.hello不是函数。 (在'this.hello()'中,'this.hello'未定义)

我还注意到在类型脚本中内置了一个名为ajaxGetJSON的函数。但我的IDE不提供如何使用此功能的文档,我无法在线查找文档。对这个问题的任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

错误是因为您使用胖函数而不是箭头1:

success: (data) => {
  this.hello();
}

因此this关键字与组件本身不对应...

话虽这么说,我会使用Angular2的Http类来加载JSON文件:

constructor(private http:Http) {
}

ngOnInit():any {
  this.http.get('../jsonfile/guestRecommendations/1.json')
          .map(res => res.json())
          .subscribe((data) => {
            this.hello();
            alert(data);
          });
}