Question

My basic premise is I want to call back to the server to get the logged in user in case someone comes to the site and is still logged in. On the page I want to call this method. Since I am passing the user service to all my controllers I don't know which controller will be in use since I won't know what page they're landing on.

I have the following User Service

app.factory('userService', function ($window) {
    var root = {};
    root.get_current_user = function(http){
        var config = {
        params: {}
    };
    http.post("/api/user/show", null, config)
        .success(function(data, status, headers, config) {
            if(data.success == true) {
                user = data.user;

                show_authenticated();
            }

        });
    };
    return root;
});

Here is an empty controller I'm trying to inject the service into

app.controller('myResourcesController', function($scope, $http, userService) {

});

So on the top of my index file I want to have something along the lines of

controller.get_current_user();

This will be called from all the pages though so I'm not sure the syntax here. All examples I found related to calling a specific controller, and usually from within another controller. Perhaps this needs to go into my angularjs somewhere and not simply within a script tag on my index page.

Was it helpful?

Solution

You could run factory initialization in run method of your angular application. https://docs.angularjs.org/guide/module#module-loading-dependencies E.g.

app.run(['userService', function(userService) {
  userService.get_current_user();
}]);

And userService factory should store authenticated user object internaly.

...
if (data.success == true) {
  root.user = data.user;
}
...

Then you will be able to use your factory in any controller

app.controller('myController', ['userService', function(userService) {
   //alert(userService.user);
}]);

OTHER TIPS

You need to inject $http through the factory constructor function, for firsts

app.factory('userService', function ($window, $http) {
    var root = {};
    root.get_current_user = function(){
        var config = {
        params: {}
    };
    $http.post("/api/user/show", null, config)
        .success(function(data, status, headers, config) {
            if(data.success == true) {
                user = data.user;

                show_authenticated();
            }

        });
    };
    return root;
});

in your controller you can say

$scope.get_current_user = UserService.get_current_user();

ng attributes in your html if needed. besides this, i am not sure what you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top