AngularJS注入器问题

Posted

技术标签:

【中文标题】AngularJS注入器问题【英文标题】:AngularJS injector issue 【发布时间】: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 代码和完整的错误信息吗? 【参考方案1】:

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

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

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

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

   return service;
)

【讨论】:

以上是关于AngularJS注入器问题的主要内容,如果未能解决你的问题,请参考以下文章

Angular 混合错误:试图在设置之前获取 AngularJS 注入器

javascript 从控制台访问注入器| AngularJS

[AngularJS面面观] 20. 依赖注入 --- instance注入器以及provider注入器

[AngularJS面面观] 21. 依赖注入 --- constant到底如何而来

AngularJs 学习笔记依赖注入

AngularJS模块具体解释