【问题标题】:How to keep route parameters even page refresh如何保持路由参数甚至页面刷新
【发布时间】:2021-01-05 13:41:31
【问题描述】:

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

first.component.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;
}

routing.module

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

【问题讨论】:

  • 你尝试使用localStorage了吗?这是浏览器上的键值存储。您可以使用 localStorage.setItem('key', 'value') 访问它。您不能直接存储文字对象,但可以执行 localStorage.setItem('key', JSON.stringify(object)) 然后检索它 JSON.parse(localStorage.getItem('key'))
  • @IvanLynch Hola Amigo。其实我想用它,但我不确定它是否常用于这种场景,也找不到这个场景的例子。你会建议我的情况吗?您能否发布一个示例代码作为答案?格拉西亚斯。

标签: javascript angular routes angular-routing angular-router


【解决方案1】:

恐怕您的代码不能按预期工作,请阅读this link关于使用状态传递数据

简单的想法是可以获取状态的值

在你去的组件中

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'])
    })

【讨论】:

  • 非常感谢这些好的解释。但我正在寻找没有服务的解决方案。我想知道在这种情况下使用 localStorage 是否是一个好主意。有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 2017-08-24
  • 1970-01-01
相关资源
最近更新 更多