2016-11-17 34 views
1

我試圖從路由器獲取數據,只要路由發生變化但我沒有成功。在這裏我設置asdf屬性如何在訂閱到Angular2的router.events.subscribe時從Route或ActivatedRoute獲取數據?

@NgModule({ 
    bootstrap: [AppComponent], 
    declarations: [ 
    AppComponent, 
    LoginComponent, 
    DashboardComponent, 
    OverviewComponent, 
    ], 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    RouterModule.forRoot([ 
     { path: '', pathMatch: 'full', redirectTo: '' }, 
     { component: LoginComponent, path: 'login' }, 
     { 
     children: [ 
      { path: '', pathMatch: 'full', redirectTo: 'overview', data: { asdf: 'hello' } }, 
      { component: OverviewComponent, path: 'overview', data: { asdf: 'hello' } }, 
     ], component: DashboardComponent, 
     path: '', 
     }, 
    ]), 
    ], 
}) 
export class AppModule { } 

在這裏,我可以從路由器得到的URL時,路線的變化,但asdf未定義:(

import { Component, OnDestroy, OnInit } from '@angular/core'; 
import { Router } from '@angular/router'; 
import { ActivatedRoute, NavigationEnd } from '@angular/router'; 
@Component({ 
    selector: 'cs-map', 
    styleUrls: ['map.component.css'], 
    templateUrl: 'map.component.html', 
}) 
export class MapComponent implements OnInit { 
    private routerSub; 

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

    public ngOnInit() { 
    this.router.events.subscribe((val) => { 
     if (val instanceof NavigationEnd) { 
     let url = val.url; 
     console.log(this.activatedRoute.snapshot.data['asdf']); // data is defined but asdf is not :(
     } 
    }); 
    } 
} 

我怎樣才能得到asdf的價值?

編輯:我導航到該路線/overview

+0

我認爲這是一個已知的問題。你可以嘗試'setTimeout(()=> console.log(this.activatedRoute.snapshot.data ['asdf']))'? –

+0

不幸的是它沒有工作 – ilovelamp

+0

今天有一個類似的問題,有人建議在'this.activatedRoute.snapshot.data'和'this.router.events'中使用'Observable.zip()'。 –

回答

4

使用此代碼,而不循環

constructor(private router: Router, 
     private activatedRoute: ActivatedRoute) 
{ 

this.router.events 
     .filter(event => event instanceof NavigationEnd) 
     .map(() => this.activatedRoute) 
     .map(route => route.firstChild) 
     .switchMap(route => route.data) 
     .map(data => data['asdf']) 
} 
+0

您能解釋它是如何工作的嗎? –

0

數據必須是對象的數組,而不僅僅是對象,以便確定他們這樣

{ component: LoginComponent, path: 'login', data:[{myKey1: myValue1}] }, 

我們檢索它在你的組件構造

constructor(private router:Router, private activeRoute:ActivatedRoute) { 

    router.events 
    .filter(event => event instanceof NavigationEnd) 
    .map(_ => this.router.routerState.root) 
    .map(route => { 
     while (route.firstChild) route = route.firstChild; 
     return route; 
    }) 
    .flatMap(route => route.data) 
    .subscribe(data => { 
    console.log(data[0].myKey1); 

    }); 

} 
+0

這不是界面所暗示的: –

+0

'''export declare type Data = { [name:string]:any; };''' –

+0

@MildFuzz它的劑量表明否則也意味着'''Data'''是'''data''的別名,類型爲'''any'',它也可以是一個數組。但是如果您訂閱router.events並檢查類型,您會看到它是arraay – Mrinmoy

相關問題