【问题标题】:Parameters routes are not redirects to page 404参数路由不重定向到 404 页
【发布时间】:2015-05-11 12:58:06
【问题描述】:

我请他们帮忙解决这个问题,按照代码:

控制器

   angular.module('tareasApp')
  .controller('HumorCtrl', function ($scope, $route, $location) { 

    $scope.pageName = $route.current.params.pageName;

$scope.items =[
 {    
      href:'/humor/smile-today', 
      img:'smile.jpg', 
      descricao:'Those Relaxing Sounds of Waves'
 }
];
 });

  angular.module('tareasApp')
  .controller('NewsCtrl', function ($scope, $route, $location) { 

    $scope.pageName = $route.current.params.pageName;

$scope.items =[
 {    
      href:'/news/news-today', 
      img:'news.jpg', 
      descricao:'Those Relaxing Sounds of Waves'
 }
];
 });

App.js

myApp.config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    $routeProvider
      .when('/', {
        title: 'Home Page',
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
       })
      .when('/humor/:pageName', {
        templateUrl: 'views/wizard.html',
        controller: 'HumorCtrl'
      })
      .when('/news/:pageName', {
          templateUrl: 'views/wizard.html',
          controller: 'NewsCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  }); 

当我在栏后键入任何不存在的路线时,例如:

domain.com/hhhoedr

返回起始页。

问题出在包含$routeParams的子目录中,输入了一个不存在的页面,例如:

domain.com/humor/hhhoedr

没有重定向到 index.html 或 404.html。

我想将此代码 I found in another answer 修改为我的应用程序。

  myApp.constant('EXISTING_PAGES', [
    'page1',
    'page2',
    ...
]);

  resolve: {
                exists: function ($location, $route) {

                    if (EXISTING_PAGES.indexOf($route.current.params.page) === -1) {

                        $location.path('/error/404');
                    }
                    return true;
                }
            }


        .when('/error/404', {
            templateUrl: '404.html'
        })
        .otherwise({
            redirectTo: '/error/404'
        });

我该怎么做?

【问题讨论】:

    标签: javascript angularjs routes


    【解决方案1】:

    当您输入任何路线e.g-domain.com/hhhoedr 时,它会返回到起始页面,因为检查您的代码的最后一部分,您将其设置如下。

    .otherwise({
            redirectTo: '/'
          });
    

    如果您将设置除所有 .when 部分之外的任何内容,它将简单地重定向到起始页面。尝试根据您的要求将其设置为重定向到任何其他页面。

    好的,现在你可以像下面这样写了。

    .otherwise({
                redirectTo: '/here give your destination path(e.g-404.html...etc)'
          });
    

    【讨论】:

    • 编辑了我的问题......你知道我可以如何将这个代码 I found in another answer 调整为我的代码吗?
    • 当使用 $routeParams 并不是那么简单。当 URL 中有错误时,$routrParams 不用说。
    猜你喜欢
    • 1970-01-01
    • 2017-10-17
    • 2021-01-01
    • 1970-01-01
    • 2019-05-11
    • 2021-05-04
    • 2017-06-01
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多