使用AngularJS $资源的jsonp请求 [英] jsonp request with AngularJS $resource

查看:92
本文介绍了使用AngularJS $资源的jsonp请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在AngularJS中定义了以下两项服务。两者都应该返回JSONP,因为我正在进行跨域请求。

I have defined the following 2 services in AngularJS. Both should return JSONP since I'm doing a cross domain request.

服务A:

angular.module('ServiceA', ['ngResource']).
  factory('A', function ($resource) {
     return $resource('url/offers', {},
       {
         get: { method: 'JSONP', params: {property_code: 'DEMO_ERFOLGX', adults: '2',
                callback: 'JSON_CALLBACK'} }
       }
    );
  });

服务B:

angular.module('ServiceB', ['ngResource']).
  factory('B', function ($resource) {
     return $resource('url/search.json', {},
       {
         get: { method: 'JSONP', params: {property_code: 'DEMO_ERFOLGX', adults: '2',
                callback: 'JSON_CALLBACK'} }
       }
    );
  });

在我的控制器中,我将结果绑定到我的范围:

In my Controller, I'm binding the result to my scope:

$scope.foo = A.get();  
$scope.bar = B.get();

根据我的console.log()输出,B以JSON格式返回预期结果,而A返回类似于:

According to my console.log() output, B returns the expected result in JSON format, while A returns something like:

SyntaxError: invalid label
{"DEMO_ERFOLGX":{"offers":[{"checkin":"2012-12-01","checkout"

我错过了什么?为了从A接收正确的JSON,我该怎么做?

Am I missing something? What do I have to do, in order to receive proper JSON from A?

推荐答案

您的代码看起来很混乱。这两个服务都被称为A,但您使用不同的模块名称。除此之外,你的第二个服务调用JSON文件而第一个服务不调用是否重要?

Your code looks confusing. Both services were called A but you use different module names. Apart from that, does it matter that your second service calls a JSON file whereas the first one doesn't?

我会尝试以下方法:

angular.module('app.services', ['ngResource'])
  .factory('ServiceA', function ($resource) {
     return $resource('url/offers', {},
       {
         get: { method: 'JSONP', params: {property_code: 'DEMO_ERFOLGX', adults: '2',
                callback: 'JSON_CALLBACK'} }
       }
    );
  });
  .factory('ServiceB', function ($resource) {
     return $resource('url/search.json', {},
       {
         get: { method: 'JSONP', params: {property_code: 'DEMO_ERFOLGX', adults: '2',
                callback: 'JSON_CALLBACK'} }
       }
    );
  });

这篇关于使用AngularJS $资源的jsonp请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆