简体   繁体   English

AngularJS-从工厂数据中解析多个.then

[英]AngularJS - Parsing multiple .then in controller from factory data

I have a controller calling to any set of specified methods in a factory to retrieve information on a given date. 我有一个控制器调用工厂中的任何一组指定方法来检索给定日期的信息。 Some of the methods iterate through a JSON file to return promise. 一些方法遍历JSON文件以返回promise。 See factory below with only two methods fleshed out. 参见下面的工厂,只有两种方法可以充实。

            emmanuel.factory('DayService', function($http, $q){
                var obj = {};
                    obj.dayInWeek = function(d){
                        // receives a mm/dd/yyyy string which then it converts it to day object to parse the weekday value
                        var date = new Date(d);
                            var weekday = new Array(
                                'sunday', 
                                'monday',
                                'tuesday',
                                'wednesday',
                                'thursday',
                                'friday',
                                'saturday'
                            );
                            return weekday[date.getDay()];
                    }
                    obj.season = function(d){
                        // receives a mm/dd/yyyy string parses against Calendar service for liturgical season
                        var day = new Date(d).getTime();
                        //$window.alert(day);
                        var promise = $q.defer();
                        $http.get('content/calendar.json').success(function(data) {
                            //$window.alert(data.calendar.seasons.season.length);
                            for (var i=0; i<data.calendar.seasons.season.length; i++){
                                var start = new Date(data.calendar.seasons.season[i].start);
                                var end = new Date(data.calendar.seasons.season[i].end);
                                end.setHours(23,59);
                                //$window.alert(start +'-'+  end +' || '+ day);
                                if (day >= start && day <= end){
                                    //$window.alert(data.calendar.seasons.season[i].name);
                                    var temp = data.calendar.seasons.season[i].name;
                                    promise.resolve(temp);
                                    //$window.alert(promise);
                                    break;
                                }
                            }
                        });

                        return promise.promise;
                    }
                    obj.weekInSeason = function(d){
                        /*...
                            return promise.promise;
                        */
                    }
                    obj.holiday = function(d){
                        /*...
                            return promise.promise;
                        */
                    }
                return obj;
            });

I was tried to write multiple temp.then(function(var) {...}); 我试图写多个temp.then(function(var){...}); for each of the methods to store the values in a $scope.date model but to my dismay only the last .then instance would store the value. 对于将值存储在$ scope.date模型中的每种方法,但令我沮丧的是,只有最后一个.then实例将存储值。

            emmanuel.controller('WeekdayMorning', function($scope, DayService){
                var tempWeek = DayService.weekInSeason(today);
                var tempSeason = DayService.season(today);

                tempWeek.then(function(week) {
                    $scope.date = {weekNum: DayService.weekInSeason(today)};
                    $scope.date = {oscWeek: week % 2};
                });

                tempSeason.then(function(season) {
                    $scope.date = {season: DayService.season(today)};
                });
            });

How can I retrieve the data from the factory promise either individual methods or as a complete $scope.date model? 如何从工厂承诺的单个方法或完整的$ scope.date模型中检索数据?

Use $q.all instead ( Official documentation for $q ): 请改用$q.all$ q的官方文档 ):

getData: function (today) {
                return $q.all([
                   DayService.weekInSeason(today),
                   DayService.season(today)
                ]);
          };

and then use then like this: then像这样使用then

getData(today).then(function(aggregatedData){
$scope.resultFromWeekInSeason = aggregatedData[0];
$scope.resultFromSeason = aggregatedData[1];
});

Note that this will only resolve when both calls have succeeded, the calls take place simultaneously. 请注意,这仅在两个呼叫都成功且呼叫同时进行时才能解决。

Promise once resolved to a value, i believe cannot change but you are trying to resolve the same promise again and again in for loop with different values. 承诺一旦解析为一个值,我相信不会改变,但是您正在尝试用不同的值在for循环中一次又一次地解决相同的诺言。 I am not sure how your scenario works, but you can use the promise notification mechanism where you can do this inside the for loop 我不确定您的方案如何工作,但是您可以使用Promise通知机制,您可以在for循环内执行此操作

promise.notify(temp);

and after the loop do 然后循环

promise.resolve({});

You can catch progress in the third parameter of then 您可以在的第三个参数中捕获进度

then(successCallback, errorCallback, notifyCallback)

The other option is to collated the temp values into an array inside a for loop. 另一个选择是将temp值整理到for循环内的数组中。

and then finally to promise.resolve(allTemps) 然后最后promise.resolve(allTemps)

Thank you all for the help. 谢谢大家的帮助。 The issue I was having was related to repeatedly declaring the model on the $scope and not multiple promises. 我遇到的问题与在$ scope上反复声明模型有关,而不是多个承诺。

Every time I re-declared $scope.date= {attr : ...} I eliminated all the previous attribute values, therefore only leaving the last declaration to contain any values. 每次我重新声明$scope.date= {attr : ...}我都会消除以前的所有属性值,因此只会保留最后一个声明中的任何值。 The right way to declare multiple attribute values to Angular $scope model is 向Angular $ scope模型声明多个属性值的正确方法是

$scope.date = { weekday: DayService.dayInWeek(today), season: DayService.season(today), weekNum: week, oscWeek: week % 2, holiday: DayService.holiday(today), nextDay: DayService.nextDay(today) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM