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

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

问题描述

我有一个包含 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.我可以看到 ConcernServiceconsole.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?

推荐答案

otherwise() 规则仅在没有其他 route 匹配时才会调用.您真正想要的是拦截 $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 本身是建立在 promises 之上的(resolve 解析),你的 ConcernService 方法可以简化为一个-liner(我意识到您出于调试目的对其进行了扩展,但您可以轻松地将其链接起来,仅供参考):

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 路由器处理 404s的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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