Angular中的jsonp

时间:2023-03-08 20:40:45
Angular中的jsonp
1、一般我们使用Angualr中的jsonp值这样使用的:注入$http服务
这样使用jsonp的方式可以支持多数api,但是douban不支持无法使用
 module.controller('InTheatersController',['$scope','$http', function($scope,$http){
var doubanApiAddress = 'https://api.douban.com/v2/movie/in_theaters'; /!*在angualr中使用jsonp服务必须在的当前地址后面加
* 一个参数callback(此名不固定)='JSON_CALLBACK',angular会将此替换为一个随机函数名 * *!/ $http.jsonp(doubanApiAddress+'?callback=JSON_CALLBACK').then(function(res){
console.log(res);
if(res.status === 200){
$scope.subjects = res.data.subjects;
}else{
$scope.message = '哎呀,获取数据失败了!'+res.statusText;
}
},function(err){
$scope.message = '哎呀,获取数据失败了2!'+err.statusText;
})
}]);

于是我们要自己写一个jsonp放服务来取代Angular中的jsonp服务

 /*
在这个组件中写一个方便跨域的服务,方便其他模块也使用 因为默认angualr提供的异步请求对象不支持自定义函数名
而angular随机分配的回调函数douban不支持
*/ 'use strict';
(function(angular){ var http = angular.module('myApp.services.http',[]); http.service('HttpService',['$window','$document',function($window,$document){ //url:https://api.douban.com/v2/movie/in_theaters放在<script>中再放在html中
this.jsonp = function(url, data, callback){
//1、处理url地址中的回调参数
//2、创建一个script标签
//3、挂载回调函数,放在全局作用域中让回调的时候执行
//4、将script放在html中 var cbFuncName = 'my_json_cb_' + Math.random().toString().replace('.', '');
// 不推荐,我们推荐angular的方式
$window[cbFuncName] = callback;//$window就是window对象 var querystring = url.indexOf('?') == -1 ? '?' : '&';
for (var key in data) {
querystring += key + '=' + data[key] + '&';
} querystring += 'callback=' + cbFuncName; //document对象是$document对象的数组成员
var scriptElement = $document[0].createElement('script');
scriptElement.src = url + querystring;
$document[0].body.appendChild(scriptElement);
}
//$window.$jsonp = jsonp;
}])
})(angular)

这样我们在模块中依赖myApp.services.http,并且注入HttpService服务就可以使用了