app.factory('userService', ['$http', function ($http) {
var userService= {},
userService.getUsers = function () {
return $http.get('getUsers');
}
userService.users =[];
return userService;
}]);
app.controller("FirstController",["$http","userService",function($http,userService){
userService.getUsers().success(function (users){
userService.users = users;//在SecondController得不到数据
})
//userService.users=[1,2,3] 如果我这样更新数据,在SecondController可以获得数组[1,2,3]
}])
app.controller("SecondController",["$http","userService",function($http,userService){
//userService.users 此得到的为空数组
//但是console.log(userService) 可以看到userService.users中有数据
}])
$http request is an asynchronous operation. When executing SecondController, there is no guarantee that the data has been obtained at this time
If you want to seal $http into your own service, you must understand $q and promise mode. At this time, you are equivalent to using synchronous thinking to perform asynchronous operations.
There are many such problems in our projects. Let me briefly talk about my current solution. Like the above, a service is encapsulated, and HTTP is used to request data. When the data is returned, a copy is stored in the cache. All controllers that require data use this service to ensure data consistency.
Generally when encapsulating servers, promises are basically used. (recommended practice)
If the questioner doesn’t want to use promises, then using callbacks can also solve the problem.
Another idea is to use event notification. When the server obtains the data, it uses the event to notify the controller.
It was said upstairs that it can be solved using callback. I tried it and it worked. Share the code. I hope it will be useful to you
send() is a keyup event to dynamically obtain the input value in the first controller