【问题标题】:Angular 4: JSONP injected script did not invoke callbackAngular 4:JSONP 注入脚本未调用回调
【发布时间】:2017-10-20 00:28:26
【问题描述】:

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

}

【问题讨论】:

  • 您好,您找到这个问题的答案了吗?我也面临同样的问题。
  • 您好 Raef,我认为我们的 API 一定有问题,可能不支持 JSONP。
  • 嗨子辰,谢谢你的回答:)
  • 嗨 Raef,非常感谢您一直为我关注这个问题。

标签: angular jsonp


【解决方案1】:

您使用 jsonp 的任何原因?因为您可以简单地编写类似的服务,

fetchUsers(){
     return this.http.get('https://jsonplaceholder.typicode.com/users')
            .map( response => response.json());
}

【讨论】:

  • 嗨 John,这是因为 api 存在一些跨域问题
  • @ZichenMa:啊.. 有道理。那么您是否尝试从不同的 URL 调用 API 并处理响应?
  • 是的,我从本地机器调用了一个 API,但该 API 托管在服务器上。另一个原因可能是因为我们的 API 不支持 JSONP,我必须从我这边弄清楚,但无论如何都非常感谢。
【解决方案2】:

使用__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);
                });
    }
}

【讨论】:

  • 这实际上解决了我的问题,但是文档声明您应该使用 JSONP_CALLBACK 替换为该字符串 __ng_jsonp____req0_finished 查看网络调用,注意缺少的“.”。这是 angular4 Jsonp 模块中的错误吗?
  • 另请注意,如果您需要多个 jsonp 请求,这肯定会失败
猜你喜欢
  • 2016-11-11
  • 2019-05-26
  • 2016-12-16
  • 2019-04-01
  • 2020-02-22
  • 2017-06-16
  • 2018-01-08
  • 2014-12-31
  • 2014-04-03
相关资源
最近更新 更多