我試圖從路由器獲取數據,只要路由發生變化但我沒有成功。在這裏我設置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
我認爲這是一個已知的問題。你可以嘗試'setTimeout(()=> console.log(this.activatedRoute.snapshot.data ['asdf']))'? –
不幸的是它沒有工作 – ilovelamp
今天有一個類似的問題,有人建議在'this.activatedRoute.snapshot.data'和'this.router.events'中使用'Observable.zip()'。 –