4

I have an app that when you select a project, it goes into the project section where it needs to load all the information and data about a project asynchronously.

I wanted to store all the data in a singleton service so I can access the data in all the project's subsections(project header, project footer, main menu, etc)

If user clicks a different project, it will need to re-initialize with different URL parameter (in this case, project_id).

app.factory('ProjectService', function($http, project_id) {
var SERVICE = {
    async: function() {
        var promise = $http.get('SOME URL' + project_id).then(function(response) {
            return response.data;
        });
        return promise;
    }
};
return SERVICE;
});

What is the best way to achieve this and how can I reinitialize the service with different URL parameters when user clicks a button?

1 Answer 1

3

Check working demo: JSFiddle

First of all, using a factory may be more suitable for your case.

You need to play with the deferred/promise manually. If the requested id is already loaded, resolve the deferred object immediately. Otherwise, send a HTTP request (in the demo I just used an public API providing fake data) and fetch the project information.

app.factory('ProjectFactory', ['$http', '$q', function ($http, $q) {
    var myProject;
    return {
        project: function (id) {
            var deferred = $q.defer();
            // If the requested id is fetched already, just resolve
            if (!id || (myProject && myProject.id === id)) {
                console.log('get from cache');
                deferred.resolve(myProject);
            } else {
                console.log('sending request...');
                $http.get('http://jsonplaceholder.typicode.com/posts/' + id).success(function (response) {
                    myProject = response;
                    deferred.resolve(myProject);
                }).error(function (response) {
                    deferred.reject(response);
                });
            }
            return deferred.promise;
        }
    };
}]);

To use this factory:

app.controller('JoyCtrl', ['$scope', '$timeout', 'ProjectFactory', function ($scope, $timeout, ProjectFactory) {
    ProjectFactory.project(1).then(function (project) {
        $scope.project = project;
        ProjectFactory.project(1).then(function (project) {
        });
    }, function (reason) {
        console.log('Failed: ' + reason);
    });
}]);

For your reference: $http, $q

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, took me some time to understand what was going on, but it worked! Thanks alot!

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.