2017-02-12 100 views
0

我是新来的AngularJS和我试图修改此代码以包裹约定在我的头:AngularJS HTTP GET范围

https://github.com/flatlogic/angular-material-dashboard/blob/master/src/app/components/services/MessagesService.js

我修改它使用REST服务取消消息而不是使用消息数组。

这里的MessageService代码:

(function(){ 
    'use strict'; 

    angular.module('app') 
     .service('messagesService', [ 
     '$scope', '$http', 
     messagesService 
    ]); 

    function messagesService($scope,$http){ 
    return { 
     loadAllItems : function() { 
     //return $q.when(messages); 
     return $http({ 
      method: 'GET', 
      url: 'http://localhost:3000/messages', 
     }) 
       .then(function(data) { 
        console.log(data); 
        return data; 
       }) 
     } 
    }; 
    } 


})(); 

但我发现了有关范围的错误:

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- messagesService 

回答

1

正如Matthew Cawley所说,服务不能访问范围。你也不能按照你的方式从loadAllItems()返回数据。

这可能是你想要与控制器例如什么:

(function() { 
    'use strict'; 

    var app = angular.module('app'); 

    app.service('messagesService', ['$http', messagesService]); 

    function messagesService($http) { 
    return { 
     loadAllItems: function() { 
     //This will make the get request and return the promise that $http sends back. 
     return $http({ 
      method: 'GET', 
      url: 'http://localhost:3000/messages', 
     }); 
     } 
    }; 
    }; 

    app.controller('testCtrl', ['$scope', "messagesService", function($scope, messagesService) { 
    //Onload 
    messagesService.loadAllItems().then(function(data) { 
     console.log(data); //Your data from the messageService 
    }, function(err) { 
     console.log(err); //Error from the messageService 
    }); 
    }]); 


}()); 

$http返回一个可以在你的控制器访问一个承诺。然后,您可以在范围内设置变量,并使数据可以被视图访问。

例:

$scope.items = data;内testCtrl。

0

采取所有引用到$scope了,你不能注入到范围一项服务。