【问题标题】:AngularJS injector issueAngularJS注入器问题
【发布时间】:2015-07-12 03:03:57
【问题描述】:

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

我收到 $injector:unpr Unknown Provider 错误。

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

var raterModule = angular.module('rater', []);

一个名为 corsService.js 的服务,它使用 enable-cors.org 中的 sn-p:

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 的控制器:

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,避免同源策略问题。

我确定这很简单,但由于我的无知,我看不到它。

【问题讨论】:

  • 你能粘贴你的 HTML 代码和完整的错误信息吗?

标签: javascript angularjs asp.net-web-api angularjs-injector


【解决方案1】:

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

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

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

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

   return service;
})

【讨论】:

    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 2017-02-04
    • 2013-11-30
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多