我创建了一个服务
来保存我的所有搜索参数。这样我就可以从任何需要的地方调用我的 $resource
并且搜索参数始终正确。这是服务
App.factory('filterService', function () {
var FilterService = {
actorId: '0001234',
actionStatus: ['BUILDING', 'STARTED', 'SENT'],
payer: null,
limit: 10,
offset: 0,
sortBy: null,
filterBy: null,
actionType: ['EB', 'AUTH'],
actorType: 'REQUESTING'
};
return FilterService;
});
因此,当我调用 REST 服务时,我可以访问如下搜索条件:
App.factory('encounterService', function ($resource, filterService) {
return {
resource: $resource('/internal/v2/encounters/:encounterId', {encounterId:'@encounterId'}, {
search: {
method: 'GET',
headers: {
'RemoteUser': 'jhornsby',
'Content-Type': 'application/json'
},
params: {
actorType: filterService.actorType,
actorId: filterService.actorId,
actionStatus: filterService.actionStatus,
actionType: filterService.actionType,
limit: filterService.limit,
offset: filterService.offset,
payer: filterService.payer,
filterBy: filterService.filterBy,
sortBy: filterService.sortBy
}
};
}
});
然后我像这样调用我的搜索
:
encounterService.resource.search({}, function(data) {
// do something with data
});
但是当我从 Controller
更新我的filterService
时,它不会更新我的filterService'。以下是更新的
filterService` 示例:
$scope.ok = function() {
// Access the filter items with this.model
filterService.actorId = $scope.model.actorId;
filterService.actionStatus = $scope.model.actionStatus;
filterService.actionType = $scope.model.actionType;
filterService.limit = $scope.model.limit;
}
每当我调用search
时,它总是使用默认值。如何将我的搜索参数转换为一个对象,就像我在这里尝试做的那样?
最佳答案
问题是,当模块初始化时,encounterService
中的 return 语句仅被调用一次。然后对搜索对象上的 params
字段进行评估,因此 filterService
在该时间点具有的值就是 params
字段的值被困住了。为了解决这个问题,您需要一种在每次想要进行查询时评估 params 对象的方法。执行此操作的一个简单方法是返回一个可以调用以获取资源的函数,而不是资源本身。
例如
App.factory('encounterService', function ($resource, filterService) {
return {
getResource: function () {
return $resource('/internal/v2/encounters/:encounterId', {encounterId:'@encounterId'}, {
search: {
method: 'GET',
headers: {
'RemoteUser': 'jhornsby',
'Content-Type': 'application/json'
},
params: {
actorType: filterService.actorType,
actorId: filterService.actorId,
actionStatus: filterService.actionStatus,
actionType: filterService.actionType,
limit: filterService.limit,
offset: filterService.offset,
payer: filterService.payer,
filterBy: filterService.filterBy,
sortBy: filterService.sortBy
}
}
};
}
}});
然后你可以这样调用:
encounterService.getResource().search({}, function(data) {
// do something with data
});
关于javascript - 我的服务没有更新 - Angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20503565/