Home  >  Q&A  >  body text

angular.js - angularjs中关于异步加载的数据在controller之间共享的问题?

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中有数据

  }])
某草草某草草2713 days ago544

reply all(5)I'll reply

  • PHPz

    PHPz2017-05-15 17:01:38

    $http request is an asynchronous operation. When executing SecondController, there is no guarantee that the data has been obtained at this time

    reply
    0
  • PHP中文网

    PHP中文网2017-05-15 17:01:38

    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.

    reply
    0
  • 某草草

    某草草2017-05-15 17:01:38

    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.

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-15 17:01:38

    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.

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-15 17:01:38

    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

    var app = angular.module("zgeApp",[]);
        app.controller('firstCtrl', ['$scope','change', function($scope,change){
            $scope.send = function(){
               change.callback($scope.name)
            }
        }])
        app.controller('secondCtrl', ['$scope','change', function($scope,change){
            change.callback = function(data){
                $scope.name1 = data;
            }                      
        }])
        app.service("change",function(){
            return {};
        })

    reply
    0
  • Cancelreply