Javascript beforeSend上的角度侦听器代码不工作
我正在使用下面的代码,我希望首先推送头,然后是请求。使用JQuery,我只需添加beforeSend,效果很好。但我已经改为AngularJS(我最喜欢的是AngularJS),我对拦截器感到困惑 让我困惑的是,如果我想先发送标题,我应该告诉它在哪里,在哪里发送标题。看一看“发送前”相关的例子并不多,我要么不理解,要么没有看到任何适合我的问题 代码: 如果我尝试不使用任何类型的拦截器,我只会得到一个未指定数据库的错误,即使我可以在浏览器开发屏幕的标题中看到它 我以前使用过$q和defer,我确实读过这可能是必需的,因为有些示例没有使用它,但这就是混淆的地方。即使延期,我在什么时候延期 提前谢谢Javascript beforeSend上的角度侦听器代码不工作,javascript,angularjs,interceptor,Javascript,Angularjs,Interceptor,我正在使用下面的代码,我希望首先推送头,然后是请求。使用JQuery,我只需添加beforeSend,效果很好。但我已经改为AngularJS(我最喜欢的是AngularJS),我对拦截器感到困惑 让我困惑的是,如果我想先发送标题,我应该告诉它在哪里,在哪里发送标题。看一看“发送前”相关的例子并不多,我要么不理解,要么没有看到任何适合我的问题 代码: 如果我尝试不使用任何类型的拦截器,我只会得到一个未指定数据库的错误,即使我可以在浏览器开发屏幕的标题中看到它 我以前使用过$q和defer,我确实
Andrew您是否在配置函数中的
$httpProvider.interceptors
数组中推送了'requestInterceptor'
?dbid从何而来?@lib3d我推送了'postComment'服务中的服务,$http.Provider.interceptors.push(requestInterceptor)代码>不在requestInterceptor服务中。这就是我做错的地方吗?@ExpertSystem dbid只是一个数字,是一个全局变量。正如我所解释的,在标题中,我可以使用浏览器开发工具看到这个数字。@Andrewalker如果$http.Provider
是对$httpProvider
的引用,它应该与$http.Provider.interceptors.push(requestInterceptor)一起工作;
或$http.Provider.interceptors.push('requestInterceptor')代码>。如果没有对提供程序的外部引用,您应该使用正常方式:App.config(function($httpProvider){$httpProvider.interceptors.push('requestInterceptor');})代码>
App.factory('postCemment', function($q,requestInterceptor, $http) {
return {
fnsend: function(sid, author, comment, callback) {
$http.Provider.interceptors.push(requestInterceptor);
$http.post("https://api.appery.io/rest/1/db/collections/comments/",
{
headers: {"Content-Type": 'application/x-www-form-urlencoded'},
params: {comment_author : author, comment : comment, statement_id : sid}
})
.success(function(commentres) {
callback(commentres);
})
}
}
})
App.factory('requestInterceptor', function() {
return {
'request': function(config) {
config.headers = {"X-Appery-Database-Id": dbid}
console.log(config);
return config;
}
}
})
App.controller('addCommentBox', function($scope, $http, $routeParams, postCemment) {
$scope.addCommentData = function() {
postCemment.fnsend($routeParams.id,$scope.aurhor,$scope.comment, function(res) {
console.log(res);
})
}
})