0

I think HTTPClient jsonp method's second parameter doesn't work as expected or I may not be understanding it correctly. Link

Below are the things I have done to use jsonp:

I have imported HttpClientJsonpModule in app.module.ts Below is the code of it

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ConstituencyStatusService } from './constituency-status.service';
import { SwitcherService } from './switcher.service'


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
   BrowserModule,
   HttpClientModule,
   HttpClientJsonpModule
  ],
  providers: [ConstituencyStatusService,SwitcherService,],
  bootstrap: [AppComponent]
})
export class AppModule { }

then I am trying to do the following but getting the error

this.http.jsonp(url,'test_callback').subscribe(data => {
  console.log(data);
});

error is ReferenceError: test_callback is not defined

My JSON output is URL is : goo.gl/6fqXq5

test_callback({ "test_url_1": "url_1", "test_url_2": "url_2", "test_url_3": "url_3", "test_url_4": "url_4", "test_url_5": "url_5", "test_url_6": "url_6", "test_url_7": "url_7" })

I see in network tab that httpclient is adding ?test_callback=ng_jsonp_callback_0 after the url

Then after some debugging I tried this json return: goo.gl/cUwx93

ng_jsonp_callback_0({ "test_url_1": "url_1", "test_url_2": "url_2", "test_url_3": "url_3", "test_url_4": "url_4", "test_url_5": "url_5", "test_url_6": "url_6", "test_url_7": "url_7" })

and it worked.

Can somebody explain why it worked now and how can I pass my custom callback function name to jsonp in Angular 5.

Pankaj
  • 585
  • 1
  • 9
  • 22

1 Answers1

0

Please can you show the url you're passing to jsonp()?

As noticed here (kcrisman comment), it looks like you're not the only one encountering a such issue.

If you're specifying the callback name as queryParam in your request, it broke things. Not specifying it and only add the callback name to jsonp() method seems to work.

You also can check the line N°1124 of HttpClient to see its behavior with JSONP_CALLBACK.

Maxime Lafarie
  • 2,172
  • 1
  • 22
  • 41