Calling only once / caching the data from a $http get in an AngularJS service

后端 未结 4 1004
春和景丽
春和景丽 2021-02-10 16:50

This may sound like a really simply/stupid question but I need to ask it as I haven\'t came across this scenario before... okay I have a service in my angularJS app. this servic

4条回答
  •  执念已碎
    2021-02-10 17:56

    To avoid timing issues, it is perhaps good to extend the solution a little bit:

    function getCities() {
            var d = $q.defer();
            if( cache ) {
                d.resolve(cache);
            }
            else {
                $http({method: 'GET', url: '/api/country/cities'}).then(
                    function success(response) {
                        if (!cache) {
                            cache = response.data;
                        }
                        d.resolve(cache);
                    },
                    function failure(reason) {
                        d.reject(reason);
                    }
                });
            }
            return d.promise;
        }
    

    After a (perhaps second or third) call to the webservice succeeds, one checks if the cache variable was set while waiting for server response. If so, we can return the already assigned value. That way, there will be no new assignment to the variable cache if multiple calls were issued:

    function success(response) {
        if (!cache) {
            cache = response.data;
    

    It does not have to make problems but if you rely on having identical objects (for example when working with data binding) it is great to be sure to only fetch data once!

提交回复
热议问题