Angular JS Initialize a service with a different parameter dynamically

I have an application that, when choosing a project, enters the project section where it needs to download all the information and data about the project asynchronously.

I wanted to store all the data in the singleton service so that I could access the data in all sections of the project (project title, project footer, main menu, etc.)

If the user clicks on another project, he will need to be reinitialized using another 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 a service with different URL parameters when a user clicks a button?

+4
source share
1 answer

Check out a working demo: JSFiddle

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

You need to play deferred / promise manually. If the requested id is already loaded, immediately resolve the pending object. Otherwise, send an HTTP request (in the demo, I just used a public API that provides fake data ) and retrieved 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 reference: $http , $q

+3
source

All Articles