Heim  >  Fragen und Antworten  >  Hauptteil

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 Tage vor542

Antworte allen(5)Ich werde antworten

  • PHPz

    PHPz2017-05-15 17:01:38

    $http请求是一个异步操作,执行SecondController时并不能保证这个时候已经获取到数据了

    Antwort
    0
  • PHP中文网

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

    你如果要把$http封到自己的服务中,必须了解$q和promise模式,此时相当于你在用同步的思想在做异步的操作。

    Antwort
    0
  • 某草草

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

    我们的项目中也有很多这种问题,简单说下我目前的解决办法。和上面一样也是封装了个service , 用http去请求数据,回来数据的时候存一份到缓存,所有controller要数据都走这个service,保证数据的一致。

    Antwort
    0
  • 巴扎黑

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

    一般封装server时基本都会用promise进行封装的。(推荐做法)

    题主不想用promise,那就使用callback也能解决问题。

    还有个思路就是使用事件通知,当server获取到数据后,利用事件通知controller.

    Antwort
    0
  • 仅有的幸福

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

    楼上说了 使用callback可以解决 我试了一下 成功了 分享一下代码,希望对你有用

    send() 是keyup事件 来动态获取 第一个控制器里面的输入值

    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 {};
        })

    Antwort
    0
  • StornierenAntwort