This question has been asked before but this is more of what style to use. Currently we have several different controllers, and we keep making a REST call to get information. For example, $http.get('/allusers')
. After we make this call, we create a user map to access each of these users. It works great but I don't like how we have to manually do this every time we need user information from the different controllers.
What I'd like is a shared object that has all the user information as a map and a shared function that will make the call and create/update the map.
This is where I start to get confused. What is the best and efficient way to approach this?
You may want to have a Factory or a Service as I tried to explain here: https://stackoverflow.com/a/39933229/1005137
You may also want to cache the response from your $http request with the following: https://docs.angularjs.org/api/ng/service/$cacheFactory
Hope this helps.
A service
would be appropriate to use in this case. This would allow you to inject it into controllers, directives and components.
angular
.module('myApp')
.service('userService', UserService);
UserService.$inject = ['$http'];
function UserService ($http) {
var service = this;
service.getAllUsers = function () {
return $http.get('/allusers');
}
}
This would then allow you to inject and use in a controller
function UserController(userService) {
userService.getAllUsers().then(function (response) {
// response.data has your goods
});
}
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.