我有两个异步函数,我需要在routeProvider的resolve部分解析其中一个。当用户在网址上键入对象时,我想自动添加一个startdate和一个enddate。我的问题是日期解决得很晚。因为如果我在Controller中执行console.log(日期表),则表明dobject
已正确解析。但这是为时已晚,我还需要调用ObjectService.get()时的日期,因为现在它只搜索/ object(生成404)而不是/ object / startdate / enddate,因为变量为null。如何在调用ObjectService.get()之前解决日期?
我的工厂和服务方法
.factory("ObjectService", ["$resource", function($resource) {
return $resource('/:object/:startdate/:enddate');
}])
.service("CurrentDates", ["DateService", function(DateService) {
this.dates = function() {
DateService.query().$promise.then(function(info) {
currentdates.startdate = info.start;
currentdates.enddate = info.end;
}).catch(onError);
return currentdates;
}
}])
.factory("DateService", ["$resource", function($resource) {
return $resource('dates.json');
}])
我的路线提供者
$routeProvider
.when('/:object', {
templateUrl: "template/table.html",
controller: 'ObjectController',
resolve: {
datetable: ["ObjectService", "CurrentDates", "$route",
function(ObjectService, CurrentDates, $route) {
var dates = CurrentDates.dates(); // dates should already be resolved here if possible
return ObjectService.get(Object.assign($route.current.params, dates)).$promise
.catch(function(errorResponse) {
return {
"error": errorResponse.status,
"object": $route.current.params.object,
"dobject": Object.assign($route.current.params, dates)
};
});
}
],
}
})
我试着这样写,但它没有用。
return CurrentDates.dates().then(function(dates) {
return ObjectService.get(Object.assign($route.current.params, dates))
.$promise.catch(function(errorResponse) {
return {
"error": errorResponse.status,
"object": $route.current.params.object,
"dobject": Object.assign($route.current.params, dates)
};
});
})
答案 0 :(得分:0)
由于Claies的提示,我设法做到了。我不得不将我的服务方法重写为:
.service("CurrentDates", ["DateService", function(DateService) {
var currentdates = {
startdate: null,
enddate: null
};
this.dates = function() {
return DateService.query().$promise.then(function(info) {
currentdates.startdate = info.start;
currentdates.enddate = info.end;
return currentdates;
}).catch(onError);
}
}])
然后我可以在routeProvider中解析变量datatable:
datetable: ["ObjectService", "CurrentDates", "$route",
function(ObjectService, CurrentDates, $route) {
return CurrentDates.dates().then(function(dates) {
return ObjectService.get(Object.assign($route.current.params, dates))
.$promise.catch(function(errorResponse) {
return {
"error": errorResponse.status,
"object": $route.current.params.object,
"dobject": Object.assign($route.current.params, dates)
};
});
})
]