Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4: JSONP injected script did not invoke callback

Tags:

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

}
like image 237
Zichen Ma Avatar asked May 19 '17 19:05

Zichen Ma


2 Answers

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);
                });
    }
}
like image 148
karthik np Avatar answered Sep 23 '22 10:09

karthik np


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());
}
like image 26
John Samuel Avatar answered Sep 24 '22 10:09

John Samuel