How to avoid duplicated http calls in the same page with angularjs?

advertisements

I have 2 controllers which have to show same data in the view (username).

How can I prevent multiple http calls? I mean, if user info is gotten already: save it to an object. if user info isn't gotten and second call came: second call must wait first call's end.

If there is another way to write this code, please tell me. I want to use this code with and without angularjs's cache method. If you suggest me use it with cache method, please tell me the alternative code without cache method.

app.controller('myController1', function (getUserInfo) {
    getUserInfo.getList().then(function (userInfo) {
        vm.userInfo = userInfo;
    });
};

app.controller('myController2', function (getUserInfo) {
    getUserInfo.getList().then(function (userInfo) {
        vm.userInfo = userInfo;
    });
};               

app.factory('getUserInfo', function ($http) {
    return {
        getList: function () {
            return $http.post('http://www.foobar.com/api')
                .then(function (response) {
                    userInfo = response.data;
                    return data;
                }, function (error) {
                    return 'Some error happened';
                });
        }
    };

});

Note: Angularjs version is: 1.5.5 and Data must be refreshed when user refreshed the page. Therefore I can't use local storage or session.


Are both controllers referencing the same vm.userInfo object? If so, you can check if vm.userInfo already contains data or not:

if(vm.userInfo.length < 1) {
    getUserInfo.getList().then(); //etc....
}