我正在尝试在$ resources URL中设置动态参数。
我发现了this有用的帖子,但遗憾的是它还没有解决我的问题。这个cid仍未填入$ resource函数。
messageApp.factory('conversationService', function($http) {
var data = {cid: ''};
$http({method: "GET", url: '/myApp/resources/conversationwizard'}, {cache: true})
.success(function(d) {
data.cid = d;
})
.error(function(data) {
alert("Could not initiate conversation" + data);
});
return data;
});
messageApp.factory('messagesService', function($resource) {
return $resource('/myApp/resources/message/all', {}, {
query: {method: 'GET', isArray: true}
});
});
messageApp.factory('messageEventPoller', function($http, $timeout, conversationService) {
var data = {data: ''};
var poller = function() {
$http.get('/myApp/msgnotification?cid=' + conversationService.cid).then(function(r) {
data.data = r.data;
$timeout(poller, 1);
});
};
poller();
return data;
});
messageApp.factory('createMessageService', function($resource, conversationService) {
return $resource('/myApp/resources/message?cid=:cid', {cid: conversationService.cid}, {
create: {method: 'POST'}
});
});
messageApp.factory('messageService', function($resource, conversationService) {
return $resource('/myApp/resources/message/:id?cid=:cid', {cid: conversationService.cid}, {
show: {method: 'GET'},
update: {method: 'PUT', params: {id: '@id'}},
delete: {method: 'DELETE', params: {id: '@id'}}
});
});
任何指针都会非常感激。
答案 0 :(得分:3)
您遇到的问题是使用单独的异步 ajax请求从服务器获取conversationService.cid
。
配置:$resource('/myApp/resources/message?cid=:cid', {cid: conversationService.cid}
时,响应尚未到达,conversationService.cid
仍为空。
不幸的是,没有简单的解决方案。在这里,我建议一些方法:
1)使用jQuery与async : false
的同步ajax :(不好阻止浏览器线程)
messageApp.factory('conversationService', function($http) {
var data = {cid: ''};
$.ajax({
url: '/myApp/resources/conversationwizard',
async : false
})
.done(function(d) {
data.cid = d;
})
.fail(function(){
alert("Could not initiate conversation" + data);
});
return data;
});
2)在引导角度之前将'/myApp/resources/conversationwizard'
加载到全局对象中(使用jQuery ajax)。在conversationService
中,您可以指定data.cid = yourglobal
;
3)使用有角度的承诺:
messageApp.factory('conversationService', function($http,$q) {
var deferred = $q.defer();
var data = {cid: ''};
$http({method: "GET", url: '/myApp/resources/conversationwizard'}, {cache: true})
.success(function(d) {
data.cid = d;
deferred.resolve(data);
})
.error(function(data) {
alert("Could not initiate conversation" + data);
});
return deferred.promise;
});
messageApp.factory('createMessageService', function($resource, conversationService) {
var deferred = $q.defer();
conversationService.then(function (data){
var createMessageService = $resource('/myApp/resources/message?cid=:cid',
{cid: data.cid},
{create: {method: 'POST'}
});
deferred.resolve(createMessageService);
});
return deferred.promise;
});
但这会增加使用资源的代码的复杂性。例如
messageApp.controller("testCtrl",function (createMessageService){
createMessageService.then(function(service){
//use your service here
});
});