我正在尝试从 AngularJS 调用 WebAPI。这是一个简单的 GET 请求,我在服务器上启用了 CORS。
我遇到了 $injector:unpr Unknown Provider 错误。
我有一个名为 raterModule.js 的 Angular 模块:
var raterModule = angular.module('rater', []);
一个名为 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 的 Controller :
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 注入(inject) menuCtrl,然后将 menuCtrl 添加到 raterModule.
menuCtrl 将使用 corsService 创建一个请求,然后发送到 WebAPI,避免同源策略问题。
我确定这很简单,但由于我的无知,我看不到它。
最佳答案
您遇到了一个错误,因为 Angular 希望您在 createCORSRequest
中注入(inject)名为 method
和 url
的提供程序,而不是函数参数。
因此,您可以通过以下方式查看您的corsService
:
raterModule.factory(`corsService`, function() {
var service = {};
service.createCORSRequest = fucntion(method, url) {
// your logic here
};
return service;
})
关于javascript - AngularJS 注入(inject)器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30001143/