ngResource默认参数

时间:2014-04-05 17:15:26

标签: angularjs

我试图使用我的变量" selectedDate'在我的休息电话中,但它总是使用旧电话,即使在使用' setSelectedDate()'设置新值之后也是如此。功能

app.factory('MyService', function ($resource) {

    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1;
    var curr_year = d.getFullYear();
    var selectedDate = curr_month + "/" + curr_date + "/" + curr_year;

    return {
        getSelectedDate : function(){
            return selectedDate;
        },
        setSelectedDate : function(newDate){
            selectedDate = newDate;
            console.log(selectedDate); // My setSelectedDate works well because I can see the new value in the console
        },

        // The selectedDate always return the first value (the new Date() ), and not the updated date
        Meal: $resource('/rest/food/meal', {date : selectedDate, mealId: '@mealId'}, {
            query: {
                method: 'GET',
                isArray: true,
                params : {date : selectedDate}

            }          
        }),
    }
});

如果我手动设置这样的参数,例如在我的控制器中,它确实有效:

FoodService.setSelectedDate(newDate);
$scope.meals = FoodService.Meal.query(FoodService.getSelectedDate());

但我希望我的服务能够自动使用' selectedDate'变量,只需要调用:

FoodService.setSelectedDate(newDate);
$scope.meals = FoodService.Meal.query();

但它总是使用旧的(第一个)日期而不是更新的日期..

有什么想法吗?

编辑:

我尝试了params,并且在$ / rest / food / meal'之后的$资源中下列 : - {date:getSelectedDate} => ReferenceError:未定义getSelectedDate - {date:getSelectedDate()} =>相同 - {date:this.getSelectedDate()} => TypeError:对象#没有方法' getSelectedDate'

最后应该工作的那个...... - {date:selectedDate}} =>是否有效,但始终使用我在第一个位置定义的第一个selectedDate,而不是更新日期

1 个答案:

答案 0 :(得分:1)

工厂需要修改如下:

app.factory('FoodService', function ($resource) {
    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1;
    var curr_year = d.getFullYear();
    var selectedDate = curr_month + "/" + curr_date + "/" + curr_year;

    function blahBlahFunction() {
      return selectedDate;
    }

    return {
        getSelectedDate : function(){
            return blahBlahFunction();
        },
        setSelectedDate : function(newDate){
            selectedDate = newDate;
            console.log(selectedDate);
        },

        Meal: $resource('/rest/food/meal', {date : blahBlahFunction, 
                                            mealId: '@mealId'}, { 
            query: {
                method: 'GET',
                isArray: true,
                params : { date : blahBlahFunction }
            }          
        }),
    }
});

注意:
params是默认的预绑定参数。为了动态地提供参数,必须将元素包装在函数中,并将函数用作参数。

这几乎违背了默认参数的概念,我认为没有上述更改的调用将是:

FoodService.Meal.query({date: "12/11/2014"});

有关详细信息,请参阅此PLUNKER。在开发工具的控制台中查找URL的错误。应该说:

GET http://run.plnkr.co/rest/food/meal?date=12%2F11%2F2014 404 (Not Found)