Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS injector issue

I'm trying to call a WebAPI from AngularJS. It is a simple GET request, and I have enabled CORS on the server.

I am getting the $injector:unpr Unknown Provider error.

I have an angular module called raterModule.js:

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

a service called corsService.js that uses the snippet from 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;
}

)

and finally a controller called 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");
                    });
    }
]);

These are all included at the bottom of an HTML index page. What I was hoping to happen would be that corsService is injected into menuCtrl, and then menuCtrl is added to the raterModule.

The menuCtrl would use corsService to create a request which is then sent to the WebAPI, avoiding the same-origin policy problem.

I'm sure it is something simple but in my ignorance I cannot see it.

like image 547
VenerableChris Avatar asked Nov 01 '22 05:11

VenerableChris


1 Answers

You've got an error because Angular expect that you gonna inject providers named method and url in your createCORSRequest, not function parameters.

So, you can review your corsService in following way:

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

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

   return service;
})
like image 174
Artem Petrosian Avatar answered Nov 15 '22 05:11

Artem Petrosian