2016-08-24 69 views
6

我已經構建了一個應用程序,它使用router 3.0.0-beta.1在應用程序部分之間切換。我還使用location.go()來模擬同一頁面的子部分之間的切換。我使用了<base href="/">和一些URL重寫規則,以便在頁面刷新的情況下將所有路由重定向到index.html。這允許路由器接收請求的子部分作爲URL參數。基本上我設法避免使用HashLocationStrategyAngular 2如何使用路由器和location.go()檢測返回按鈕按下?

routes.ts

export const routes: RouterConfig = [ 
    { 
     path: '', 
     redirectTo: '/catalog', 
     pathMatch: 'full' 
    }, 
    { 
     path: 'catalog', 
     component: CatalogComponent 
    }, 
    { 
     path: 'catalog/:topCategory', 
     component: CatalogComponent 
    }, 
    { 
     path: 'summary', 
     component: SummaryComponent 
    } 
]; 

如果我在導航欄中點擊某款2件事情:

  • logation.go()更新必要的字符串的URL,以指示當前
  • 自定義scrollTo()動畫會滾動請求子部分頂部的頁面。

如果我刷新頁面,我正在使用先前定義的路徑並提取必要的參數以將滾動恢復到請求的子部分。

this._activatedRoute.params 
    .map(params => params['topCategory']) 
    .subscribe(topCategory => { 
     if (typeof topCategory !== 'undefined' && 
      topCategory !== null 
     ) { 
      self.UiState.startArrowWasDismised = true; 
      self.UiState.selectedTopCategory = topCategory; 
     } 
    }); 

所有工作正常,除非我點擊後退按鈕。如果上一頁是不同的部分,則應用程序路由器將按預期行事。但是,如果上一頁/網址是子網段,則網址會更改爲上一個網址,但在用戶界面中不會發生任何變化。如何檢測後退按鈕是否被按下以調用scrollTo()函數再次執行作業?

大多數答案我relly看到了事件onhashchange,但這一事件並沒有在我的應用程序會被解僱,因爲我有畢竟URL中有散...

+1

https://stackoverflow.com/questions/35912932/angular-2-router-event-listener看到 –

回答

1

使用onpopstate事件的伎倆:

window.addEventListener('popstate', 
    // Add your callback here 
    () => self.events.scrollToTopCategory.emit({ categId: self.state.selectedTopCategory }) 
); 
3

我與阿德里安Moisa答案達成一致,

但你可以用「多棱角2路」注入到你的組件或服務使用PlatformLocation類,那麼你可以onPopState回調定義是這樣的:

this.location.onPopState(()=>{ 
    // your code here... 
    this.logger.debug('onpopstate event'); 
}); 
+2

的onPopState的問題在於,即使用戶前進,也會引發該事件。 –

3

我不知道答案的日期,但在角2.我所做的是通過將它導入到我的組件添加一個角2事件偵聽器都沒有工作很適合我:

import { HostListener } from '@angular/core'; 

,然後popstatewindow對象上偵聽(阿德里安推薦):

@HostListener('window:popstate', ['$event']) 
    onPopState(event) { 
    console.log('Back button pressed'); 
    } 

此代碼對我的作品在最新的角2。

2

要檢測瀏覽器的後退按鈕,點擊來自「 進口platformlocation @角/通用並把下面的代碼在構造函數:

constructor(location: PlatformLocation) { 
    location.onPopState(() => { 
     alert(window.location); 
    }); } 
2

角文檔直接國PlatformLocation類...

  • 該類不應直接由應用程序開發人員使用。

我用LocationStrategy在構造

constructor(location: LocationStrategy) { 
      location.onPopState(() => { 
      alert(window.location); 
     }); 

}