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: "[email protected]", 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?

1 Answer 1

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

}]);
Sign up to request clarification or add additional context in comments.

2 Comments

I return currentUser to requestCurrentUser function. This is no problem. I use your guide, but I get undefined error when I echo $scope.user.
I find another solution, but your guide is shorter and easier and work fine. Another solution: stackoverflow.com/questions/13088153/…

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.