0

I want use a service in a angular.module.

I have a record.js for RecordCtrl and I want use requestCurrentUser fnction that exist in sessionService.js. I use Session for pass data between controller and service. I send a request from record,js by requestCurrentUser function like below:

'use strict';
var app = angular.module('app');
app.controller('RecordCtrl',['$scope','Session','Records',function($scope, Session, Records){
    $scope.user = Session.requestCurrentUser();
}]);

and I recieve this in sessionService.js like below:

  'use strict';
   angular.module('sessionService', [])
    .factory('Session', function($location, $http, $q) {
        var service = {

            requestCurrentUser: function() {
                    return $http.get('/api/users').then(function(response) {
                        service.currentUser = response.data.user;
                        return service.currentUser;
                    );
                }
            },
            currentUser: null,
        return service;
    });

I can get data correctly in requestCurrentUser, but I cannot recieve this data in record.js. When I echo data in sessionService.js, I can see below data:

Object {id: 2, email: "mgh@mgh.com", created_at: "2014-08-11T08:37:59.981Z", updated_at: "2014-08-26T08:03:27.702Z"} 

But I cannot recieve this data in record.js and I get an empty object like below:

[object Object] 

I think the problem of code is about Session that I use in 2 js file(record.js and sessionService.js). For add dependency, I have a app.js that include dependencies on this.

app.js:

'use strict';
angular.module('app',['ngRoute', 'ngResource', 'sessionService', 'recordService'])

I cannot find the problem, I add sessionService.js to record.js by below code:

app.service('sessionService');

But the problem isn't fix. I don't know how can I resolve this problem? Any one have idea for fix this problem?

mgh
  • 921
  • 3
  • 9
  • 37

1 Answers1

2

It can be fixed as follows:

'use strict';
var app = angular.module('app');
app.controller('RecordCtrl',['$scope','Session','Records',function($scope, Session, Records){
    Session.requestCurrentUser().then(function(data) {
        $scope.user = data;
    });

}]);
khemry
  • 585
  • 3
  • 7
  • I return `currentUser` to `requestCurrentUser` function. This is no problem. I use your guide, but I get `undefined` error when I echo `$scope.user`. – mgh Aug 26 '14 at 09:27
  • I find another solution, but your guide is shorter and easier and work fine. Another solution: http://stackoverflow.com/questions/13088153/how-to-http-synchronous-call-with-angularjs – mgh Aug 27 '14 at 08:33