简体   繁体   English

如何处理AngularJS路由找不到的资源

[英]How to handle resource not found with AngularJS routing

In a traditional data driven web application we often attempt to load a resource based on an ID passed in the URL. 在传统的数据驱动的Web应用程序中,我们经常尝试根据URL中传递的ID加载资源。 If the resource does not exist we return a 404 page. 如果资源不存在,我们返回404页面。

How should we achieve the same thing in AngularJS? 我们应该如何在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): 我已经按照AngularJS电话目录教程进行操作,如果资源不存在,我目前正在执行以下操作(注意这使用了Angular $resource服务):

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
        }
      });
}]);

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 ? 考虑到我需要在几乎所有资源上执行此操作,我想知道在$routeProvider是否会更好地处理它?

I usually use ngRoute and provide resources through resovle: 我通常使用ngRoute并通过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
             }]
         }
    });
}]);

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 然后,如果要显示错误页面,则需要监听$routeChangeError事件

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

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 如果您有多个资源,这种方法允许您将错误处理代码保存在一个位置,并从这个逻辑中清除控制器非常方便

在内部ngResource使用$ http所以处理这种情况你可以使用http拦截器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM