2015-05-02 28 views
5

Tôi đang cố gọi một WebAPI từ AngularJS. Nó là một yêu cầu GET đơn giản, và tôi đã kích hoạt CORS trên máy chủ.AngularJS injector issue

Tôi nhận được $ injector: un Unknown Provider lỗi.

Tôi có một mô-đun góc gọi raterModule.js:

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

một dịch vụ gọi corsService.js có sử dụng đoạn mã từ 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; 
} 

)

và cuối cùng là bộ điều khiển được gọi là 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"); 
        }); 
    } 
]); 

Tất cả đều được bao gồm ở cuối trang chỉ mục HTML. Những gì tôi đã hy vọng để xảy ra sẽ là corsService được tiêm vào menuCtrl, và sau đó menuCtrl được thêm vào raterModule.

MenuCtrl sẽ sử dụng corsService để tạo yêu cầu sau đó được gửi tới WebAPI, tránh vấn đề chính sách gốc.

Tôi chắc chắn nó là một cái gì đó đơn giản nhưng trong sự thiếu hiểu biết của tôi, tôi không thể nhìn thấy nó.

+0

Bạn có thể dán mã HTML của bạn và cũng có thể được thông báo lỗi đầy đủ? –

Trả lời

2

Bạn gặp lỗi vì Angular hy vọng bạn sẽ bơm các nhà cung cấp có tên methodurl trong số createCORSRequest của bạn, chứ không phải thông số chức năng.

Vì vậy, bạn có thể xem corsService của bạn theo cách sau:

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

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

    return service; 
}) 
+0

Cảm ơn, hiện đang làm việc. – VenerableChris