我正在制作摄影师可以用来上传照片的应用程序。前端是AngularJS,还有一个RESTfull api后端。
由于一些问题以及ui-router似乎比ngRouter更好的事实,我决定将$ routeprovider更改为ui-router的$ stateProvider。
然而,我的决心不再起作用(我猜它会破裂,但我无法找到解决方案)。
所以这是原始的$ routeprovider代码:
.when('/photographer', {
templateUrl : '/static/partials/photographer/photographer_dash.html',
controller : 'photographerController',
resolve: {
photogPrepService: function (PhotogService) {
return PhotogService.ownPhotos();
}
}
})
PhotogService是一个$ resource服务,它具有以下$ resource对象:
return $resource(apiHost, {}, {
'ownPhotos': {
url: apiHost + '/photographer_own_photos/',
method: 'GET',
interceptor: ResponseInterceptor
}
});
在控制器中,我会执行以下操作(因为解析而注入了photogPrepService):
var promise = photogPrepService;
promise.then(
function (data) {
$scope.ownPhotos = data.data.photos;
});
这一切都运作良好,我会把照片放在范围内。
然而,正如ui-router所说,它不起作用,我似乎无法让它工作......
根据文档(https://github.com/angular-ui/ui-router/wiki#resolve),以下内容应该有效:
$stateProvider.state('photographer',
{
url: '/photographer',
templateUrl: '/static/partials/photographer/photographer_dash.html',
controller: 'photographerController',
resolve: {
photogPrepService: function (PhotogService) {
return PhotogService.ownPhotos();
}
}
但是,当在控制器中注入解析并使用console.log()打印响应时,我得到以下内容:
Resource(value)
我似乎无法将值(JSON响应{“photos”:...})注入到控制器中。我尝试了各种解决方案,这些解决方案已在stackoverflow和读取指南以及ui-的API上提出路由器,但我无法解决出错的问题......我希望有人可以指导我朝正确的方向发展..
谢谢!
答案 0 :(得分:0)
I think you can use the code below:
//the PhotogService will keep the same as before
//inject the 'PhotogService' into the controller photographerController
PhotogService.ownPhotos().then(function(data) {
$scope.ownPhotos = data.data.photos;
});
//instead of injecting the photogPrepService through 'resove', inject the PhotogService into the controller
//for the $stateProvider
$stateProvider.state('photographer',
{
url: '/photographer',
templateUrl: '/static/partials/photographer/photographer_dash.html',
controller: 'photographerController',
}
答案 1 :(得分:0)
You need to give a promise to the resolve, your ressource should look more like :
$stateProvider.state('photographer',
{
url: '/photographer',
templateUrl: '/static/partials/photographer/photographer_dash.html',
controller: 'photographerController',
resolve: {
photogPrepService: function (PhotogService) {
return PhotogService.ownPhotos().$promise;
}
}
});
Or modify your ressources to make them promises.