How to implement back button in Angular for navigating previous page?

為{幸葍}努か 提交于 2021-01-01 08:10:41

问题


I have a list-component where I want to keep the pageIndex value by setting some variables in another class just before navigating to another component let's say x-component. Then, when navigating back to the list-component, I want to get the previously set pageIndex so that open that page instead of opening the first page on the datatable. So, what is an alegant way to fix this problem without using a service or subcribtion? I can use another class, but not a service. I tried to retrieve the set values from a class, but pageIndex value is undefined when trying to retrieve it.

Any help would be appreciated.


回答1:


You can also have the pageIndex as a URL param of the page where list-component is rendered.

Inject in your ctor:

private route: ActivatedRoute

Then in your ngOnInit do something like:

this.route.params.subscribe((params: any) => {
    if (params.pageIndex) {
        this.pageIndex = params.pageIndex;
    }
});

In your routing module your URL should match: some-url/:pageIndex. And when paging back and forth in the list the URL should be updated accordingly.




回答2:


You can use sessionStorage.

In x-component, save pageIndex with this.

sessionStorage.setItem('pageIndex', pageIndex);

Then load this value in list-component like this.

public pageIndex = Number(sessionStorage.getItem('pageIndex') ?? 0);



回答3:


import { Location } from '@angular/common';

previousUrl: string;
constructor(private location: Location,private router: Router){ }

goBackFunction(){
router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {

      console.log('prev:', event.url);
      this.previousUrl = event.url;
});

 this.location.back()  
}

It will take you to the previous page :)



来源:https://stackoverflow.com/questions/65398669/how-to-implement-back-button-in-angular-for-navigating-previous-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!