標籤:地址 src .com api 非同步請求 amp rip pen log
1、一般我們使用Angualr中的jsonp值這樣使用的:注入$http服務
這樣使用jsonp的方式可以支援多數api,但是douban不支援無法使用
1 module.controller(‘InTheatersController‘,[‘$scope‘,‘$http‘, function($scope,$http){ 2 4 var doubanApiAddress = ‘https://api.douban.com/v2/movie/in_theaters‘; 5 6 /!*在angualr中使用jsonp服務必須在的當前地址後面加 7 * 一個參數callback(此名不固定)=‘JSON_CALLBACK‘,angular會將此替換為一個隨機函數名 * *!/ 8 9 $http.jsonp(doubanApiAddress+‘?callback=JSON_CALLBACK‘).then(function(res){10 console.log(res);11 if(res.status === 200){12 $scope.subjects = res.data.subjects;13 }else{14 $scope.message = ‘哎呀,擷取資料失敗了!‘+res.statusText;15 }16 },function(err){17 $scope.message = ‘哎呀,擷取資料失敗了2!‘+err.statusText;18 })19 }]);
於是我們要自己寫一個jsonp放服務來取代Angular中的jsonp服務
1 /* 2 在這個組件中寫一個方便跨域的服務,方便其他模組也使用 3 4 因為預設angualr提供的非同步請求對象不支援自訂函數名 5 而angular隨機分配的回呼函數douban不支援 6 */ 7 8 ‘use strict‘; 9 (function(angular){10 11 var http = angular.module(‘myApp.services.http‘,[]);12 13 http.service(‘HttpService‘,[‘$window‘,‘$document‘,function($window,$document){14 15 //url:https://api.douban.com/v2/movie/in_theaters放在<script>中再放在html中16 this.jsonp = function(url, data, callback){17 //1、處理url地址中的回調參數18 //2、建立一個script標籤19 //3、掛載回呼函數,放在全域範圍中讓回調的時候執行20 //4、將script放在html中21 22 var cbFuncName = ‘my_json_cb_‘ + Math.random().toString().replace(‘.‘, ‘‘);23 // 不推薦,我們推薦angular的方式24 $window[cbFuncName] = callback;//$window就是window對象25 26 var querystring = url.indexOf(‘?‘) == -1 ? ‘?‘ : ‘&‘;27 for (var key in data) {28 querystring += key + ‘=‘ + data[key] + ‘&‘;29 }30 31 querystring += ‘callback=‘ + cbFuncName;32 33 //document對象是$document對象的數群組成員34 var scriptElement = $document[0].createElement(‘script‘);35 scriptElement.src = url + querystring;36 $document[0].body.appendChild(scriptElement);37 }38 //$window.$jsonp = jsonp;39 }])40 })(angular)
這樣我們在模組中依賴myApp.services.http,並且注入HttpService服務就可以使用了
Angular中的jsonp