Detect Back button pressed in Angular2

前端 未结 2 1337
不知归路
不知归路 2020-12-21 14:55

I\'m trying to detect if the back button was pressed when I load this component. In the ngOnInit(), I\'d like to know if Back was clicked so I don\'t clear all my filters. H

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 15:47

    create a variable in service , initialize it to false and set it to true inside the ngOnInit method.Since service gets initialized only once , add in ngOnInit :-

     ngOnInit(){
        if(!this._filterService.flag) this._filterService.clear()
      this._filterService.flag = true;
      //rest of your code
     }
    

    Make sure service is initialized only once ,i.e when app is bootstrapped and not inside component's metadata.If page is refreshed , flag value will be false initially and true if component is accessed using back button

提交回复
热议问题