0

In my app.config i need to retrieve a value from a service but i have an error message : UserServiceProvider.getUser is not a function. The goal is to allow the user to access some pages only if he is a part of a list.

Here's my service code :

var app =  angular.module('myApp');
  app.service('UserService', '$http', '$q', function(){
   userService.getUser = function () {
        var deferred = $q.defer();
        return $http.get(userUrl + "getUserName")
             .success(function (data) {
                 deferred.resolve(userService.userName = data);
                 console.log(data);
                 //alert('Success loading user');
             }).error(function (error) {
                 deferred.reject(error);
                 //alert('Error loading user' + error.message);
             })
        return deferred.promise;
    }
    return userService;
  });

My config :

  app.config(function(UserServiceProvider){
     UserServiceProvider.getUser()
      .then(function (data) {
          console.log(UserServiceProvider.userName);
      });
  });
10
  • 2
    Possible duplicate of How to inject a service into app.config in AngularJS Commented Nov 9, 2015 at 21:32
  • I read that post, but i cannot comment since i dont have enough point reputations. So i changed my initial question Commented Nov 10, 2015 at 13:42
  • according to this. you should call .$get() on the provider first to get the instance, then call your method. I haven't tested it myself. Commented Nov 10, 2015 at 14:31
  • That works ! but when i try to display the userName in the index.html doing this : .state('/', { url: '/', templateUrl: 'index.html', controller: 'userCtrl', resolve: { user: function () { return {userName : userFromProvider}; } } }) It says : WARNING: Tried to load angular more than once. There a way to pass the userName without using state ? Commented Nov 10, 2015 at 16:34
  • Is the purpose of injecting the service into app.config so that you can use it in your routes/state definitions? Because there is a better way to do this. Commented Nov 10, 2015 at 16:55

0

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.