0

I want to load a local JSON file for testing purposes in my angular2 app written in typescript. I have 1) Included the jQuery.d.ts file, and tried to use $.getJson() 2) tried $.ajax() with async:false. The problem with both of these is that I cannot call functions outside of the callback function.

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

}

This errror is thrown EXCEPTION: TypeError: this.hello is not a function. (In 'this.hello()', 'this.hello' is undefined)

I have also noticed that there is a function built into type script called ajaxGetJSON. But my IDE does not provides docs for how to use this function and I cannot find docs online for it. Any help with this question would be great.

slipperypete
  • 5,358
  • 17
  • 59
  • 99

1 Answers1

0

The error is because you use a fat function instead of an arrow one:

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

So the this keyword doesn't correspond to the component itself...

That being said, I would use the Http class of Angular2 to load a JSON file:

constructor(private http:Http) {
}

ngOnInit():any {
  this.http.get('../jsonfile/guestRecommendations/1.json')
          .map(res => res.json())
          .subscribe((data) => {
            this.hello();
            alert(data);
          });
}
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • I have tried your second suggestion and the typescript compiler throws an error Error:(28, 14) TS2339: Property 'map' does not exist on type 'Observable'. Do you know why this is? – slipperypete Jun 03 '16 at 13:24
  • You need to import the operator. This question could help you: http://stackoverflow.com/questions/34515173/angular-2-http-get-with-typescript-error-http-get-map-is-not-a-function-in/34515276#34515276. – Thierry Templier Jun 03 '16 at 13:27
  • I've added import 'rxjs/add/operator/map'; and still get the error. – slipperypete Jun 03 '16 at 13:52
  • This solution along with another post solved my problem. http://stackoverflow.com/questions/37618012/why-do-i-get-the-error-property-map-does-not-exist-on-type-observablerespon – slipperypete Jun 03 '16 at 16:06