项目需要开发一个类似于微信打开网页时底部的前进后退按钮组件,能够根据路由所处栈中的位置来确定按钮是否前进后退,以及改变按钮相应的颜色,这就需要自己制作一个页面栈出来。

思路是通过HTML5的history.length属性能够知道在浏览器页面历史中存在的页面数量,同时监听angualrrouter获取当前页面的路由将其添加到自己的页面栈中。

1.每次进入页面时,首先判断页面栈中是否存在该路由,没有就push进去。

2.当栈中的路由数量超过浏览器历史栈长度时,就将多余的页面删除,这样能保证自己的页面栈始终与浏览器的页面栈相同。

3.获取当前路由在页面栈中的位置,通过索引与栈长度对页面元素的样式进行改变。

微信图片_20191128151355.png

详细实现过程如下:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
  selector: 'app-foot',
  templateUrl: './foot.component.html',
  styleUrls: ['./foot.component.scss']
})
export class FootComponent implements OnInit {
  routerArr = [];  //页面栈
  routerPath = ''; //当前路由
  idx = 0;         //当前路由索引

  constructor(
    private route: Router
  ) {
    // 打开应用时,判断历史栈长度为1就清空缓存中的页面栈
    if (history.length == 1) {
      localStorage.removeItem("routerArr");
    }
    let storageRouter = JSON.parse(localStorage.getItem("routerArr"));
    storageRouter ? this.routerArr = storageRouter : '';
    // 监听页面路由变化
    this.route.events.subscribe((data) => {
      //路由导航结束之后
      if (data instanceof NavigationEnd) {
        // 当前页面路由
        this.routerPath = data.url.substr(1);
        if (this.routerPath == "") {
          this.routerPath = "home";
        }
        // 添加新路由进页面栈
        if (!this.routerArr.includes(this.routerPath)) {
          this.routerArr.push(this.routerPath);
          //若页面栈长度超出浏览器历史栈长度就删除历史长度的前一位至新页面之间的页面
          if (this.routerArr.length > history.length) {
            this.routerArr.splice(history.length - 1, this.routerArr.length - history.length);
          }
        }
        // 当前路由在页面栈中的索引
        this.idx = this.routerArr.indexOf(this.routerPath) + 1;
        localStorage.setItem("routerArr", JSON.stringify(this.routerArr));
      }
    })
  }
  ngOnInit() {}
  // 后退
  goBack() {
    history.go(-1);
  }
  // 前进
  goAhead() {
    history.go(1);
  }
}

郝幸运
-2 声望0 粉丝

码不死的农民