Angular;激活”;数据出来后的手表

Angular, "activate" a watch after data has come in

本文关键字:手表 数据 激活 Angular      更新时间:2023-09-26

我正在尝试在作用域上设置$watch,这样我就可以侦听更改,但是,我不希望在数据进入并填充之前,watch开始侦听。我使用$q工厂,然后填充项目,然后我希望手表在填充完所有内容后开始监听。我似乎记不清如何控制这些事件的顺序。

所以我的控制器里有

//call to the $q factoy to execut all http calls
getDefaults.resource.then(function(data){
    //fill in scopes with data
    $scope.allAccounts = data[0].data.accounts;
    //THEN watch the scope for changes
    $scope.$watch('selectedResources', function (newValue) { 
        //do action on change here
    });
}

所以我想知道是否有任何方法可以控制这些事件的角度顺序。感谢阅读!

您可以为xhr调用创建一个服务:

.factory('xhrService', function ($http) {
    return {
        getData: function () {
             return $http.get('/your/url').then(cb);
        }
    };
    function cb(data) {
       /// process data if you need
       return data.accounts;
    }
});

之后,你可以在你的控制器中这样使用它:

.controller('myController', function (xhrService) {
    $scope.allAccounts = [];
    xhrService.getData()
        .then(function (accounts) {
            $scope.allAccounts = accounts;
            return $scope.allAccounts;
        })
        .then(function () {
           $scope.$watch('allAccounts', function (newValue) {
              // do something
           } 
        });
});

我认为这是一个构建代码的好方法,因为你可以重用你的服务,你可以添加(或不添加)你需要的任何手表(在任何控制器内)

最重要的是,从文档来看:https://docs.angularjs.org/api/ng/service/$q-"$q.then方法返回一个新promise,该promise通过successCallback的返回值errorCallback被解析或拒绝"-这就是为什么每个then callback都需要一个return语句。