I am new to Anguar4 and met this question:
JSONP injected script did not invoke callback
I tried different API for example: https://jsonplaceholder.typicode.com/posts
However, my api gives me this error. However, it works for jQuery, jsonp. I googled many resources online, spent many hours, but could n't fix it. Here is my code:
import { Injectable } from '@angular/core';
import { Http, Headers, Jsonp, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ServerService{
constructor(private jsonp: Jsonp){}
getServers(term: string) {
let url = `url`;
let params = new URLSearchParams();
params.set('search', term); // the user's search value
params.set('action', 'opensearch');
params.set('format', 'json');
params.set('callback', 'JSONP_CALLBACK');
return this.jsonp
.get(url, { search: params })
.subscribe(
(data) => {
console.log(data);
},
(error) => {
console.log(error);
});
}
}
Use __ng_jsonp__.__req0.finished
instead of JSONP_CALLBACK
!
import { Injectable } from '@angular/core';
import { Http, Headers, Jsonp, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MyServerService{
constructor(private jsonp: Jsonp){}
getServers(term: string) {
let url = `https://jsonplaceholder.typicode.com/posts`;
let params = new URLSearchParams();
params.set('search', term); // the user's search value
params.set('action', 'opensearch');
params.set('format', 'json');
params.set('callback', '__ng_jsonp__.__req0.finished');
return this.jsonp
.get(url, { search: params })
.subscribe(
(data) => {
console.log(data);
},
(error) => {
console.log(error);
});
}
}
Any reason you are using jsonp ? because you can simply write a service something like,
fetchUsers(){
return this.http.get('https://jsonplaceholder.typicode.com/users')
.map( response => response.json());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With