2017-04-20 29 views
4

我在我的應用程序路由模塊定義了一些路線數據象下面這樣:如何獲得數據路由到應用程序組件在角2

const appRoutes:Routes = [ 
    {path: '', component: LoginComponent, data:[{PageName:"Login Page"}]}] 

我想在全球範圍內獲取數據,所以我用app.component。 TS得到URL重定向相關信息如下:

export class AppComponent { 
    title = 'Welcome'; 
    constructor(public router: Router, public authenticationService: AuthenticationService) { 
    this.router.events.subscribe(event => { 
     console.log("Url",event.urlAfterRedirects); 
     console.log("Page Name", router[PageName]); //Not working 
     } 

我試過注射ActivatedRoute但它沒有得到每個重定向後更新。

有無論如何,我可以配置頁面名稱,並在全球範圍內獲取它app.component.ts

回答

8

嘗試filter和循環的事件,而不是subscribe

constructor(router:Router, route:ActivatedRoute) { 
    router.events 
     .filter(e => e instanceof NavigationEnd) 
     .forEach(e => { 
     this.title = route.root.firstChild.snapshot.data['PageName']; 
    }); 
} 

請檢查下面的工作演示:https://plnkr.co/edit/rBToHRaukDlrSKcLGavh?p=info

+0

我將上面的代碼添加到我的app.component.ts。我得到的值是未定義的。 – user1188867

+0

你可以創建一個運動員嗎?這很難幫助你。正如你看到我的工作演示的作品,所以我們非常接近解決你的問題:) –

+0

我道歉它的一個大項目與多個模塊,我不能創建plunker出來。 – user1188867

0
export class AppComponent implements OnInit, OnDestroy{ 
    title = 'Welcome'; 
    private paramsSubscription; 

    constructor(public router: Router, 
       private activatedRoute: ActivatedRoute, 
       public authenticationService: AuthenticationService) {} 


public ngOnInit() { 
    this.paramsSubscription = this.activatedRoute.params 
     .subscribe((params) => { 
     console.log("Page Name", params['PageName']); 
     }   
} 

// Unsubscribe route params to avoid memmory leaks 
public ngOnDestroy() { 
    this.paramsSubscription.unsubscribe(); 
} 
+2

它不工作,並沒有得到每一條路線的要求 – user1188867

1

如果你在靜態使用路由路由器對象象下面這樣:

{path:'',pathMatch:'full',component:NameComponen噸,數據:{VARIABLENAME: 'variableValue'}},

在ngOnInit()可以使用ActivatedRoute對象來恢復從路由器定義傳遞的數據:

ngOnInit(){ 此.localVariable = this.route.snapshot.data ['variableName']; }

Obs:我正在使用Angular 5!

相關問題