在 Angular 中显示应用内错误消息的最佳方式

Best way to display in-app error messages in Angular

我一直在尝试找出处理从 Angular 中的 API 返回 204/404 的最佳方法。我当前的平面只是删除当前视图,而是显示一个给用户消息的框。

这似乎是 $http.interceptors 的工作,所以我设置了我的配置:

angular.module('myApp', [])
    .config(function($stateProvider, $urlProvider, $httpProvider, myUrls) {
        $stateProvider
            .state('home', {
                url: '/home',
                controller: 'HomeCtrl',
                templateUrl: '/path/to/template/home.html'
            })

            .state('error', {
                url: '/error',
                controller: 'ErrorCtrl',
                templateUrl: '/path/to/template/error.html'
            });

        $httpProvider.interceptors.push(function() {
            return {
                response: function(res) {
                    if(res.config.url === myUrls.data && [204, 404].indexOf(res.status) > -1) {
                        // show the error message
                    }
                }
            };
        });
    })

    .constant('myUrls', { data: '/api/endpoint' });

问题是,如果我添加尝试将依赖项注入 $state 到我的 $httpProvider 中,以便我可以使用 $state.go 导航到错误页面,我创建了一个循环依赖项:

Uncaught Error: [$injector:cdep] Circular dependency found: $http <- $templateFactory <- $view <- $state <- $http

我错过了什么吗?返回特定状态代码时,是否有更好的方法向用户触发 status/exception 消息?我是否应该为此目的使用 ui.router

有几种方法可以解决这个循环依赖问题。例如:

  • 在 $rootScope 上发出事件,让一些服务观察事件并在接收到事件时使用 $state
  • 注入$injector,并在需要时按名称从注入器获取$state服务