2015-05-02 11 views
5

Sto provando a chiamare WebAPI da AngularJS. È una semplice richiesta GET e ho abilitato CORS sul server.Problema dell'iniettore AngularJS

Sto ricevendo il $ injector: unpr Unknown Provider error.

Ho un modulo angolare chiamato raterModule.js:

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

un servizio chiamato corsService.js che utilizza il frammento 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; 
} 

)

e infine un controller denominato 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"); 
        }); 
    } 
]); 

Questi sono tutti inclusi in fondo a una pagina HTML indice. Quello che speravo per accadere sarebbe che corsService viene iniettato in MenuCtrl, e quindi MenuCtrl viene aggiunto al raterModule.

Il menuCtrl utilizza corsService per creare una richiesta che viene quindi inviata a WebAPI, evitando il problema della politica dell'origine stessa.

Sono sicuro che è qualcosa di semplice ma nella mia ignoranza non riesco a vederlo.

+0

Puoi incollare il codice HTML e anche il messaggio di errore completo? –

risposta

2

Hai un errore perché Angular si aspetta che tu inserisca i provider denominati method e url nel tuo createCORSRequest, non i parametri di funzione.

Quindi, è possibile rivedere il tuo corsService in modo seguente:

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

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

    return service; 
}) 
+0

Grazie, adesso. – VenerableChris