2016-08-02 29 views
1

我試圖檢測加載此組件時是否按下了後退按鈕。在ngOnInit()中,我想知道Back是否被點擊,所以我不清除我所有的過濾器。下面是代碼:在Angular2中按下檢測返回按鈕

export class ProductListComponent implements OnInit, OnDestroy { 
constructor (private _productsService: ProductsService, params: RouteParams, private _categoriesService: CategoriesService, private _filtersService: FiltersService, private _router: Router, private _location: Location) { 
    this.category = params.get('name') ? params.get('name') : null; 
} 

subscription: any; 
category: any; 
loading: boolean = false; 
page: number = 1; 
count: number; 
products: any; 
pages: Array = []; 
errorMessage: string; 

ngOnInit() { 

    this.getProducts(); 

    //if(back button wasnt used) { 
    // this._filtersService.clear(); 
    //} 

    this.subscription = this._filtersService.filterUpdate.subscribe(
     (filters) => { 
      this.page = 1; 
      var params = this.category ? {name: this.category} : {}; 
      this._router.navigate([this.currentRoute, params]); 
      this.getProducts(); 
     } 
    ); 
} 
+0

是關於keydown事件而非選項? – Jinjubei

+0

我需要檢測它是否回撥 – Karl

回答

-1

創建服務的變量,它初始化爲false,並將其設置爲ngOnInit method.Since服務中真正得到一次初始化,加入ngOnInit: -

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

確保服務只初始化一次,即當應用程序被引導時,而不是在組件的元數據中。如果頁面被刷新,則標誌值將最初爲假,如果使用後退按鈕訪問組件,則該值爲true

+0

這不完全是我需要的,我需要知道何時按下後退按鈕,所以我不會調用該服務操作。否則稱它 – Karl