-1

I need to make JSONP calls from my Angular 4 application, unfortunately the target api only allows certain callback parameters but I can't see how to set the callback function in Angular.

I want to change the value but callbackParam only changes the name.

e.g. http://myapi/data?callback=THIS_NEEDS_TO_BE_CHANGED

Daaavvy
  • 333
  • 3
  • 10

1 Answers1

0

Just finished trying to figure this out myself. My solution felt like a bit of a hack but got the job done.

I make the jsonp callback in a tag in my index.html so its globally available.

<script>
    window.THIS_NEEDS_TO_BE_CHANGED = function(data){
      console.log("jsonp callback");
      window.angularServiceRef.service.callComplete(data);
    }
  </script>

In the class I would normally subscribe to the jsonp call. I give the window object a reference to the class, make an 'in angular' handler, and also pull in ngzone.

//service class 
constructor(private zone: NgZone){
    window['angularServiceRef'] = {service: this};
}
//...
public callComplete(data: any): void {  // This gets called from index.html   // this is the jsonp callback handler hack.
        console.log('callback complete');
        this.zone.run(() => {this.someData = data }); // Since callComplete() is run from outside angular, zonejs lets this code run back within angulars scope.

}

The callComplete() function gets the data from the THIS_NEEDS_TO_BE_CHANGED callback, then assigns the data to the service class variable. This happens in a zone block so that it's picked up by the change listeners.

This answer for calling angular from outside the scope helped. Angular2 - how to call component function from outside the app

Mark D
  • 233
  • 3
  • 17