如何保持路由参数甚至页面刷新



我使用以下方法通过不同的路由传递参数,并试图在页面刷新或打开路由页面上的另一个选项卡时保留这些参数值。但是,在检索这些参数后,它们丢失了值。那么,在路线上不使用:id等后缀的情况下,是否可以保持它们的值?在这个场景中,我首先打开SecondComponent,然后使用选项卡打开它的子级SecondChildComponent。

第一个组件.ts

details(name) {
this.router.navigate(['/second'], { state: { name: name} });
}

second.component.ts

constructor(private router: Router) {
this.name= this.router.getCurrentNavigation().extras.state.name;
}

路由模块

const routes: Routes = [
{
path: 'second',
component: SecondComponent,
children: [
{
path: '',
redirectTo: 'second-child',
},
{
path: 'second-child',
component: SecondChildComponent
}
]
}
];

恐怕您的代码不能像您预期的那样工作,请阅读关于使用状态传递数据的链接

简单的想法是,您可以获得状态的值

在你去的组件

ngOnInit() {
this.activatedRoute.paramMap
.pipe(map(() => window.history.state)).subscribe(res=>{
console.log(res)
})
}

在";主要成分";使用

ngOnInit() {
this.router.events.pipe(
filter(e => e instanceof NavigationStart),
map(() => this.router.getCurrentNavigation().extras.state)
).subscribe(res=>{
console.log(res)
})
}

关于你的问题,唯一的";对象";当你改变路线时保持的是一个";服务";。唯一的";对象";当你";刷新";是localStore,或者在服务器中使用某种备份之王。

使用服务,只需具有

@Injectable({
providedIn: 'root',
})
export class DataService {
data:any;
constructor() { }
}

并使用

.subscribe(res=>{
this.dataService.data=res.name || this.dataService.data
this.name=this.dataService.data
})

另一个途径是若你们并没有收到一个参数路由器到第一个组件。这个想法可以使用,例如,如果你有一个典型的组件,它有一个带有按钮编辑的表;细节";组成部分如果";细节";不接收到带有表的组件的值路由

.subscribe(res=>{
if (!res.name)
this.router.navigateTo(['/table'])
})

最新更新