AngularJS UI路由器处理404 [英] AngularJS UI router handling 404s

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

问题描述

我有一个带有服务的应用程序,该服务包装了我的API调用:

I have an app with a service which wraps my API calls:

var ConcernService = {
    ...
    get: function (items_url, objId) {
        var defer = $q.defer();
        $http({method: 'GET', 
            url: api_url + items_url + objId}).
            success(function (data, status, headers, config) {
                defer.resolve(data);
            }).error(function (data, status, headers, config) {
                console.log('ConcernService.get status',status);
                defer.reject(status);
            });
        return defer.promise;
    },

我正在使用UI-Router在状态之间进行转换:

and I'm using UI-Router to transition between states:

concernsApp

    .config( function ($stateProvider, $urlRouterProvider) {

        $urlRouterProvider.otherwise("/404/");


        $stateProvider.state('project', {
        url: '/project/:projectId/',
        resolve: {
            project: function ($stateParams, ConcernService) {
                return ConcernService.get('projects/', $stateParams.projectId);
            },
        },
        views: {
            ...
        }
    });

我不再使用普通的AngularJS路由器,并且难以理解如何实现404.我可以看到ConcernService抛出console.log状态被拒绝,但是如何在状态路由器中捕获它呢?

I'm moving from using the normal AngularJS router and I'm having difficulty understanding how to implement 404s. I can see the ConcernService throwing the console.log status as rejected, but how do I catch this in the state router?

推荐答案

仅当没有其他 route 匹配时,才调用otherwise()规则.您真正想要的是拦截$stateChangeError事件,该事件是在状态转换中发生问题(例如,解析失败)时触发的.您可以在状态更改事件文档中了解有关此内容的更多信息.

The otherwise() rule is only invoked when no other route matches. What you really want is to intercept the $stateChangeError event, which is what gets fired when something goes wrong in a state transition (for example, a resolve failing). You can read more about that in the state change event docs.

您要执行的操作的最简单实现是这样的:

The simplest implementation for what you're trying to do would be something like this:

$rootScope.$on('$stateChangeError', function(event) {
  $state.go('404');
});

此外,由于$http本身是基于promise(resolve可以解决的)构建的,因此您的ConcernService方法可以简化为单一格式(我意识到您将其扩展用于调试目的,但是您可以就像链接一样简单,仅供参考):

Also, since $http itself is built on promises (which resolve resolves), your ConcernService method can be simplified down to a one-liner (I realize you expanded it for debugging purposes, but you could have just as easily chained it, just FYI):

var ConcernService = {

  get: function (items_url, objId) {
    return $http.get(api_url + items_url + objId);
  }
}

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

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