$location.path 在使用 AngularJS 的工厂中不会改变

编程入门 行业动态 更新时间:2024-10-08 08:22:13
本文介绍了$location.path 在使用 AngularJS 的工厂中不会改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我的工厂看起来像:

'use strict';

angular.module('myApp')
  .factory('httpInterceptor',['$q','$location', '$rootScope', function($q, $location, $rootScope){
    return {
      response: function(response) {

        if(response.success === false) {
console.log("Redirecting");
            $location.path('/login');
            return $q.reject(response);
        }

        return response || $q.when(response);
      }
    }
}]);

它会吐出日志,但不会更改路径.我该怎么做才能做到这一点?

It spits out the log, but doesn't change the path. What can I do to make this happen?

推荐答案

$location 的文档 说:

请注意,setter 不会立即更新 window.location.相反,$location 服务知道作用域生命周期,并在作用域 $digest 阶段将多个 $location 突变合并为一个对 window.location 对象的提交".

Note that the setters don't update window.location immediately. Instead, the $location service is aware of the scope life-cycle and coalesces multiple $location mutations into one "commit" to the window.location object during the scope $digest phase.

因此,如果拒绝承诺对 $location 有影响,那么您可能看不到预期的更改.

Hence, if the rejection of the promise has an effect on $location, then you may not see the intended change.

要强制在 angular 生命周期之外进行更改,您可以使用 window.location 设置 hash,然后强制重新加载页面.当然,这将停止执行随后的任何代码并清除会话,但如果用户未登录,这可能是您想要的.

To force a change outside of the angular life-cycle, you can set the hash using window.location and then force a reload of the page. This will, of course, stop execution of any code which follows and erase the session, but that might be what you want if the user is not logged in.

这篇关于$location.path 在使用 AngularJS 的工厂中不会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 17:23:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1007786.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:工厂   location   path   AngularJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!