AngularJS ui-router 解析 REST 资源



我正在开发一个摄影师可以用来上传照片的应用程序。前端是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 响应 {"照片":...})注入控制器。我尝试了在堆栈溢出和阅读指南以及ui-router的API上建议的各种解决方案,但是我无法弄清楚出了什么问题......我希望有人能引导我朝着正确的方向前进。

谢谢!

我认为您可以使用以下代码:

//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',
}

你需要对决心做出承诺,你的资源应该看起来更像:

$stateProvider.state('photographer',
{
  url: '/photographer',
  templateUrl: '/static/partials/photographer/photographer_dash.html',
  controller: 'photographerController',
  resolve: {
    photogPrepService: function (PhotogService) {
      return PhotogService.ownPhotos().$promise;
    }
  }
});

或者修改你的资源,让他们做出承诺。

最新更新