如何处理资源与AngularJS路由发现 [英] How to handle resource not found with AngularJS routing

查看:95
本文介绍了如何处理资源与AngularJS路由发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在传统的数据驱动的Web应用程序,我们常常试图基于URL传送ID的加载资源。如果资源不存在,我们返回404页。

In a traditional data driven web application we often attempt to load a resource based on an ID passed in the URL. If the resource does not exist we return a 404 page.

我们应该如何实现AngularJS是一回事吗?我跟着AngularJS电话目录教程,我目前做以下应在资源不存在(注意这里使用了角 $资源服务):

How should we achieve the same thing in AngularJS? I've followed the AngularJS phone catalog tutorial and am currently doing the following should the resource not exist (note this uses the Angular $resource service):

controllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', '$location', 'Phone',
  function($scope, $routeParams, $location, Phone) {

    $scope.phone = Phone.get({ phoneId: $routeParams.phoneId }, 
      function(phone) {
        $scope.mainImageUrl = phone.images[0];
      },
      function(response) {
        if (response.status === 404) {
          $location.path('/404'); // show phone not found page
        }
      });
}]);

这是建议的方法?考虑到我需要做的几乎所有资源我不知道是否会在更好地处理的 $ routeProvider

Is this the recommended approach? Considering I will need to do this on virtually every resource I wondered whether it would be better handled within the $routeProvider?

推荐答案

我通常使用 ngRoute 并通过resovle提供资源:

I usually use ngRoute and provide resources through resovle:

angular.module('myApp').config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/phone/:phoneId', {
         templateUrl: 'views/phone.html',
         controller: 'PhoneDetailCtrl',
         resolve: {
             phone: ['$route', 'Phone', function($route, Phone) {
                 return Phone.get({ phoneId: $route.current.params.phoneId }).$promise
             }]
         }
    });
}]);

现在手机宣布为这条航线的依赖和路由时响应返回一个错误将不会改变。然后,如果你想显示你需要听 $ routeChangeError 错误页面事件

Now phone declared as dependency of this route and route won't be changed when response return an error. Then if you want to show error page you need listen to $routeChangeError event

angular.module('myApp').run(['$rootScope', '$location', function($rootScope, $location) {
   $rootScope.$on('$routeChangeError', function(event, current, previous, error) {
       if(error.status === 404) {
          $location.path('/404');
       }
   });
}]);

如果您有多个资源,这种方法允许你把错误处理code在一个地方,清晰控制器从这个逻辑,这是非常方便的。

If you have multiple resources this approach allow you keep error handling code in one place and clear controllers from this logic that is very convenient

这篇关于如何处理资源与AngularJS路由发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆