0

I'm new to AngularJS and I'm trying to modify this code to wrap my head around the conventions:

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

I'm modifying it to use a REST service to fetch messages instead of using the messages array.

Here's the MessageService code:

(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;
                })
      }
    };
  }


})();

But I'm getting an error about the scope:

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

2 Answers 2

1

As Matthew Cawley said, services cannot access scope. Nor can you return data from loadAllItems() the way you are.

This is probably what you want with a controller example:

(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 returns a promise that can be accessed in your controller. You can then set your variable in scope and make the data accessible to the view.

Ex:

$scope.items = data; within testCtrl.

Sign up to request clarification or add additional context in comments.

Comments

0

Take all of your references to $scope out, you can't inject scope into a service.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.