java和angular网页制作_在angular中制作自己的页面栈

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

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

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

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

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

70c0dface4545ce73d6859bd05f71297.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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值