我是Anguar4的新手,遇到了这个问题:
JSONP注入脚本没有调用回调
我尝试了不同的API,例如: https://jsonplaceholder.typicode.com/posts
然而,我的api给了我这个错误。但是,它适用于jQuery,jsonp。我在网上搜索了很多资源,花了很多时间,但无法修复它。这是我的代码:
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);
});
}
}
答案 0 :(得分:3)
使用__ng_jsonp__.__req0.finished
代替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);
});
}
}
答案 1 :(得分:0)
您使用jsonp的任何原因?因为你可以简单地写一个类似的服务,
fetchUsers(){
return this.http.get('https://jsonplaceholder.typicode.com/users')
.map( response => response.json());
}