Wscats / articles

🔖My Learning Notes and Memories - 分享我的学习片段和与你的回忆

Home Page:https://github.com/Wscats/articles

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Angular自定义判断上一页是否存在的服务

Wscats opened this issue · comments

当我们从一个页面跳进一个新页面的时候,有时候我们会需要判断是否存在上一个页面
在Javascript中有一个方法原生方法可以实现
document.referrer
定义和用法:referrer 属性可返回载入当前文档的文档的 URL。
w3school是这样说明它的:如果当前文档不是通过超级链接访问的,则为 null。这个属性允许客户端 JavaScript 访问 HTTP 引用头部。

<html>
<body>
The referrer of this document is:
<script type="text/javascript">
document.write(document.referrer)
</script>
</body>
</html>

由于这个是比较常用的方法,我把它写成一个Angular的服务来方便调用,在用到的地方再注入referrer这个服务就可以实现对应的方法
写的很简单,具体如下:

<!DOCTYPE html>
<html ng-app="wsscat" ng-controller="serCtrl">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no">
        <title></title>
        <script type="text/javascript" src="ng.js"></script>
    </head>
    <body>
    </body>
    <script>
        var app = angular.module('wsscat', []);
        app.controller('serCtrl', function($scope, cat, referrer) {
            referrer.log();
        })
        app.service('referrer', function() {
            var obj = {
                url: function() {
                    var url = document.referrer ? document.referrer : '';
                    return url;
                },
                back: function() {
                    window.history.go(-1);
                },
                //判断是否有上一页,如果有则返回,没有则在
                is: function() {
                    this.url ? this.back() : '';
                },
                log: function() {
                    console.log('当前页为:' + window.location.href);
                    console.log('上一页为:' + this.url());
                }
            }
            return obj;
        });
    </script>
</html>

这里把常用的返回刷新列出来,实际情况可以根据需求用相对应的替换掉服务中的window.location.href

  • history.back(-1):直接返回当前页的上一页,数据全部消息,是个新页面
  • history.go(-1):也是返回当前页的上一页,不过表单里的数据全部还在
  • history.back(0) 刷新 history.back(1) 前进 history.back(-1) 后退
  • window.location.reload();//刷新
  • window.history.go(1);//前进
  • window.history.go(-1);//返回+刷新
  • window.history.forward();//前进
  • window.history.back();//返回

需要注意的是必须从一个页面跳到这个例子的页面才会触发document.referrer,刷新页面等referrer都会返回空,路由切换视图的跳转的也是不成功的,原因在于视图切换其实本质上是异步的刷新页面

如果要返回上一个路由,我觉得可以从routeChangeSuccess下手

$rootScope.$on('$routeChangeSuccess',
                    function() {
$rootScope.loginBack = window.location.href;
})

可以把当前的页面记录下来保存到一个全局的loginBack中,然后根据情况再去返回对应的路由
还有一个在Angular里面挺好用的跟原生一样的函数
$window.history.length
length 属性声明了浏览器历史列表中的元素数量
有什么地方可以用到了,如果你是刚进来这个页面则返回的是1
如果你是路由中切换了几次那么这个值肯定会大于1
所以我们可以用这个方法来判断我们是否首次加载进入这个Angular框架
甚至我们还可以用它来监听用户切换过多少次路由,来获取相应的信息