Javascript AngularJS喷油器问题
我正在尝试从AngularJS调用WebAPI。这是一个简单的GET请求,我已经在服务器上启用了CORS 我收到$injector:unpr未知提供程序错误 我有一个称为raterModule.js的角度模块:Javascript AngularJS喷油器问题,javascript,angularjs,asp.net-web-api,angularjs-injector,Javascript,Angularjs,Asp.net Web Api,Angularjs Injector,我正在尝试从AngularJS调用WebAPI。这是一个简单的GET请求,我已经在服务器上启用了CORS 我收到$injector:unpr未知提供程序错误 我有一个称为raterModule.js的角度模块: var raterModule = angular.module('rater', []); raterModule.controller("menuCtrl",["$scope","$http","corsService", function menuCtrl($scope,
var raterModule = angular.module('rater', []);
raterModule.controller("menuCtrl",["$scope","$http","corsService",
function menuCtrl($scope, $http, corsService) {
var xhr = corsService.createCORSRequest('GET', 'http://localhost:50942/api/menu/items');
if (!xhr) {
throw new Error('CORS not supported');
}
// Getting menu items
$http.get(xhr)
.success(function (data, status, headers, config) {
$scope.menu = data;
})
.error(function (data, status, headers, config) {
alert("error getting menu items");
});
}
]);
名为corsService.js的服务,使用enable-cors.org中的代码段:
raterModule.factory("corsService",
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
if ("withCredentials" in xhr) {
xhr.withCredentials = true;
xhr.open(method, url, true);
}
// Otherwise, check if XDomainRequest. XDomainRequest only exists in IE, and is IE's way of making CORS requests.
else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
}
// Otherwise, CORS is not supported by the browser.
else {
xhr = null;
}
return xhr;
}
)
最后是一个名为menuController.js的控制器:
var raterModule = angular.module('rater', []);
raterModule.controller("menuCtrl",["$scope","$http","corsService",
function menuCtrl($scope, $http, corsService) {
var xhr = corsService.createCORSRequest('GET', 'http://localhost:50942/api/menu/items');
if (!xhr) {
throw new Error('CORS not supported');
}
// Getting menu items
$http.get(xhr)
.success(function (data, status, headers, config) {
$scope.menu = data;
})
.error(function (data, status, headers, config) {
alert("error getting menu items");
});
}
]);
这些都包含在HTML索引页面的底部。我希望发生的是将corsService注入menuCtrl,然后将menuCtrl添加到raterModule
menuCtrl将使用corsService创建一个请求,然后将该请求发送到WebAPI,从而避免同源策略问题
我确信它很简单,但我不知道我看不到它。您有一个错误,因为您希望在您的
createCORSRequest
中插入名为method
和url
的提供者,而不是函数参数
因此,您可以通过以下方式查看您的corsService
:
raterModule.factory(`corsService`, function() {
var service = {};
service.createCORSRequest = fucntion(method, url) {
// your logic here
};
return service;
})
你能粘贴你的HTML代码和完整的错误信息吗?