How do I detect user navigating back in Angular2?

前端 未结 6 1761
离开以前
离开以前 2020-11-27 15:01

I have a component and I need to detect if user pressed back button in his browser to navigate back.

Currently I\'m subscribing router events.

constr         


        
6条回答
  •  孤独总比滥情好
    2020-11-27 15:56

    IMO better method of listenting for popstate events is to subscribe to location service

    import {Location} from "@angular/common";
    
    constructor(private location: Location) { }
    
    ngOnInit() {
        this.location.subscribe(x => console.log(x));
    }
    

    It doesn't use PlatformLocation directly (as documentation suggest) and you can unsubscribe any time you want.

提交回复
热议问题