【问题标题】:AngularJS Http Interceptor, Show Bootstrap AlertAngularJS Http 拦截器,显示引导警报
【发布时间】:2023-03-12 13:28:01
【问题描述】:

我喜欢在每次请求完成时显示一个警告框。为了缩短我的方式,我喜欢使用“引导警报”。似乎无法访问工厂内的任何范围。我怎么能意识到这样的事情?

app.factory('httpInterceptor', function ($q) {
    return {
        // On request success
        request: function (config) {
            $scope.alerts.push({msg: "Request done !"}); //There is no scope
            return config || $q.when(config);
        },
        // On request failure
        requestError: function (rejection) {
            return $q.reject(rejection);
        },
        // On response success
        response: function (response) {
            return response || $q.when(response);
        },
        // On response failure
        responseError: function (rejection) {
            return $q.reject(rejection);
        }
    };
});

请参阅http://angular-ui.github.io/bootstrap/ 上的警报示例

【问题讨论】:

  • 我想你可以在这里注入$rootScope。试试看。使用 $rootScope.$broadcast 方法引发事件并在某些控制器中捕获它以显示稍后。

标签: javascript angularjs


【解决方案1】:

您可以创建一个将被注入到拦截器和作用域中的服务:

.factory('alerts',

function () {

    var alerts = [];

    return {

        getAlerts: function () {
            return alerts;
        },

        addAlert: function (msg) {
            alerts.push({ msg: msg });
        },

        closeAlert: function (index) {
            alerts.splice(index, 1);
        }
    }
 }) 

在作用域的控制器中这样使用它:

function($scope, alerts) {
    $scope.alerts = alerts.getAlerts();
}

在拦截器本身:

alerts.addAlert('msg');

【讨论】:

    【解决方案2】:

    我知道这个问题已经很老了,也许 OP 找到了更好的解决方案,但我在这里提供答案作为对那些没有找到解决方案的人的参考。

    我们可以利用 bootstrap 提供的 $broadcast 方法。在此处阅读有关 $broadcast 的更多信息:https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$broadcast

    app.factory('httpInterceptor', function ($q) {
        return {
            // On request success
            request: function (config) {
                $rootScope.$broadcast("requestDone");               
                return config || $q.when(config);
            },
            // On request failure
            requestError: function (rejection) {
                return $q.reject(rejection);
            },
            // On response success
            response: function (response) {
                return response || $q.when(response);
            },
            // On response failure
            responseError: function (rejection) {
                return $q.reject(rejection);
            }
        };
    });
    

    在您的控制器中,只需按以下方式监听事件:

    $rootScope.$on("loginStatus", function(e) {
      $scope.alerts.push({msg: "Request done !"}); //There is scope  
    });
    

    干杯!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 2019-09-23
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多