AngularJS喷油器问题

Ven*_*ris 5 javascript asp.net-web-api angularjs angularjs-injector

我正试图从AngularJS调用WebAPI.这是一个简单的GET请求,我在服务器上启用了CORS.

我收到$ injector:unpr未知提供程序错误.

我有一个名为raterModule.js的角度模块:

var raterModule = angular.module('rater', []);
Run Code Online (Sandbox Code Playgroud)

一个名为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;
}
Run Code Online (Sandbox Code Playgroud)

)

最后是一个名为menuController.js的控制器:

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");
                    });
    }
]);
Run Code Online (Sandbox Code Playgroud)

这些都包含在HTML索引页面的底部.我希望发生的是将corsService注入menuCtrl,然后将menuCtrl添加到raterModule.

menuCtrl将使用corsService创建一个请求,然后将该请求发送到WebAPI,从而避免同源策略问题.

我确信它很简单,但在我的无知中,我看不到它.

Art*_*ian 2

你遇到了一个错误,因为 Angular 期望你在你的 中注入名为method和 的提供程序,而不是函数参数。urlcreateCORSRequest

因此,您可以corsService通过以下方式查看您的情况:

raterModule.factory(`corsService`, function() {
    var service = {};

    service.createCORSRequest = fucntion(method, url) {
    // your logic here
    };

   return service;
})
Run Code Online (Sandbox Code Playgroud)