配置
(function() {
angular.module('plunker', ['ngRoute']);
angular.module('plunker').config(['$routeProvider', moduleConfig]);
function moduleConfig($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html', //url of the template
controller: 'HomeCtrl', //name of the controller
controllerAs: 'hCtrl' //how it should be referred in the template
})
.when('/profile', {
templateUrl: 'profile.html', //url of the template
controller: 'ProfileCtrl', //name of the controller
controllerAs: 'pCtrl' //how it should be referred in the template
})
.otherwise({
redirectTo: '/home'
});
}
//controllers should be in their own .js files
angular.module('plunker').controller('HomeCtrl', HomeCtrl);
angular.module('plunker').controller('ProfileCtrl',['myservice', ProfileCtrl]);
function HomeCtrl() {
var hCtrl = this;
alert('HomeCtrl');
}
function ProfileCtrl(myservice) {
var pCtrl = this;
myservice.retrive(function(data){
alert('profile');
});
}
})();
我的服务
(function(){
angular.module('plunker')
.factory('myservice',myservice);
myservice.$inject=['$http'];
function myservice($http) {
var factory={
retrive:retrive
};
return factory;
function retrive(callback){
var url = 'test.json';
var params = {
callback: 'angular.callbacks._0'
};
$http.jsonp(url, {params: params}).then(callback);
}
}
})();
我为特定页面编写了这个 Controller 和服务,比如说“/profile”。配置文件 Controller 使用具有 JSONP 请求的服务。当我转到该页面(“/profile”)时,一切正常并且 JSONP 回调执行。但是,当我在“/profile”之后转到“/index”并再次返回“/profile”时,JSONP 调用会触发,但 Controller 中的回调不会执行。有人能发现这个错误吗
plnkr 代码 http://plnkr.co/edit/fswywkpsH6xl5XU0YplK?p=preview
在此 plnkr 中,配置文件 Controller 中的回调仅执行一次
最佳答案
问题是 Angular 会在内部增加 jsonp 回调值作为跟踪机制
您必须使用记录的查询字符串?callback=JSON_CALLBACK
。
值 JSON_CALLBACK
只是一个占位符,$http
将在内部替换为以下值:
angular.callbacks._0
angular.callbacks._1
angular.callbacks._2
您的实现问题是您始终返回 angular.callbacks._0()
,因此下一个需要 angular.callbacks._1()
的调用不会收到该值,因此将拒绝请求
将您的服务方式更改为:
function retrive(callback){
var url = 'test.json';
var params = {
callback: 'JSON_CALLBACK'
};
$http.jsonp(url, {params: params}).then(callback ).catch(function(err){
console.log(err)
});
}
在您的演示中,您将看到第二个请求的 err.status
为 404
关于javascript - Angular jsonp 回调仅执行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597716/