简体   繁体   中英

Angular Global Variables

I've got the following code in my Angular app that sets a global user variable. I want to know if what I've written can be refactored to a better way. I don't know why but firing the setUser() function on app.run feels a bit clunky? Can the following be improved?

app.run()

app.run(function ($user) {
    $user.setUser();
});

app.service('$user')

app.service('$user', ['$http', function ($http) {    
    var currentUser;
    this.setUser = function () {
        $http.get('/users/active/profile')
            .success(function (user) {
                currentUser = user;
            })
            .error(function () {
                console.log('ERR');
            })
    }    
    this.getUser = function () {
        return currentUser;
    }    
}]);

You could do something like this.

app.service('$user', ['$http', function ($http) {

    var currentUser;

    var usrSrv = {
        setUser : function () {
            currentUser = "test user";
            console.log( "user Set" );
        },
        getUser : function() {
            return currentUser;
        }
    };

    usrSrv.setUser();
    return usrSrv;

}]);

You may also want to look into using angular promises ( https://docs.angularjs.org/api/ng/service/ $q), since this is a async call. Depending on the context and your design, you may want to change the service to just expose a getUser method, The getUser method will make the http call and return a promise that gets resolved when it has fetched the results from the server.

Try doing below:

(function () {
var userService = function ($http) {

    var setUser = function () {
        $http.get('/users/active/profile')
            .success(function (user) {
                var currentUser = user;
            })
            .error(function () {
                console.log('ERR');
            });
    };

    return {
        currentUser: currentUser,
    };

};
var module = angular.module("app");

module.factory("userService", userService);
}());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM