Javascript 如何在 Angular 2 中将路由数据获取到 App 组件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43512695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Route data into App Component in Angular 2
提问by user1188867
I have defined some route data in my app routing module like below:
我在我的应用路由模块中定义了一些路由数据,如下所示:
const appRoutes:Routes = [
{path: '', component: LoginComponent, data:[{PageName:"Login Page"}]}]
I want to get the data globally so that I can use appRoutes in app.component.ts to get the URL redirection related information as below:
我想全局获取数据,以便我可以在 app.component.ts 中使用 appRoutes 获取 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
}
I tried injecting ActivatedRoute but it's not getting updated after each redirection.
我尝试注入 ActivatedRoute,但在每次重定向后都没有更新。
Is there anyway, where I can configure page name and get it in global app.component.ts.
无论如何,我可以在哪里配置页面名称并在 global 中获取它app.component.ts。
回答by Hristo Eftimov
Try to filterand loop your events instead of subscribe
尝试filter循环您的事件而不是subscribe
constructor(router:Router, route:ActivatedRoute) {
router.events
.filter(e => e instanceof NavigationEnd)
.forEach(e => {
this.title = route.root.firstChild.snapshot.data['PageName'];
});
}
Please check the following working demo: https://plnkr.co/edit/rBToHRaukDlrSKcLGavh?p=info
请检查以下工作演示:https: //plnkr.co/edit/rBToHRaukDlrSKcLGavh?p=info
回答by Pablo
If you had statically routed using Router object like below:
如果您使用 Router 对象进行静态路由,如下所示:
{
path: '',
pathMatch: 'full',
component: NameComponent,
data: { variableName: 'variableValue' }
},
On ngOnInit() you can use ActivatedRoute object to recover the data you passed from Router definition:
在 ngOnInit() 上,您可以使用 ActivatedRoute 对象来恢复从路由器定义传递的数据:
ngOnInit() {
this.localVariable = this.route.snapshot.data['variableName'];
}
Obs: I am using Angular 5!
Obs:我正在使用 Angular 5!
回答by danday74
This code was written by Todd Motto (Google Developer Expert) to access route data in a parent component or app component. Works like a gem.
此代码由 Todd Motto(Google 开发专家)编写,用于访问父组件或应用程序组件中的路由数据。像宝石一样工作。
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'
import { filter, map, mergeMap } from 'rxjs/operators'
constructor(private route: ActivatedRoute, private router: Router) {}
ngOnInit() {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.route),
map(route => {
while (route.firstChild) route = route.firstChild
return route
}),
filter(route => route.outlet === 'primary'),
mergeMap(route => route.data)
).subscribe(data =>
console.log('data', data)
)
}
See: https://ultimatecourses.com/blog/dynamic-page-titles-angular-2-router-events
请参阅:https: //ultimatecourses.com/blog/dynamic-page-titles-angular-2-router-events
In his example he is using route data to set the page title in app component.
在他的示例中,他使用路由数据在应用程序组件中设置页面标题。
Why accessing route data in a parent is so complicated I'll never know!
为什么访问父级中的路由数据如此复杂,我永远不会知道!
回答by FaustmannChr
For Angular 5+
对于 Angular 5+
This service retrieves data on the current route: (in my case "title")
此服务检索当前路线上的数据:(在我的情况下为“标题”)
import { Injectable } from "@angular/core";
import { Router, ActivatedRouteSnapshot } from "@angular/router";
@Injectable()
export class AppRoutingService {
constructor(private router: Router) { }
public getRouteTitle(): string {
return this.getRouteData("title");
}
private getRouteData(data: string): any {
const root = this.router.routerState.snapshot.root;
return this.lastChild(root).data[0][data];
}
private lastChild(route: ActivatedRouteSnapshot): ActivatedRouteSnapshot {
if (route.firstChild) {
return this.lastChild(route.firstChild);
} else {
return route;
}
}
}
Component Logic:
组件逻辑:
import { Component, OnInit, OnDestroy } from "@angular/core";
import { Router, NavigationEnd } from "@angular/router";
// SERVICES
import { RouterService } from "../../shared/services/router.service";
@Component()
export class NavSubmenuComponent implements OnInit, OnDestroy {
title: string = "";
routerEvents: any;
constructor(private router: Router, private routerService: RouterService) { }
ngOnInit() {
this.title = this.routerService.getRouteTitle();
this.routerEvents = this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(() => {
this.title = this.routerService.getRouteTitle();
});
}
ngOnDestroy() {
this.routerEvents.unsubscribe();
}
}
回答by andrebarata
If you are willing to wait until the ngAfterViewInit event you can link to the router outlet using viewchild.
如果您愿意等到 ngAfterViewInit 事件发生,您可以使用 viewchild 链接到路由器插座。
i.e.
IE
@ViewChild('router')
private routerOutlet: RouterOutlet;
ngAfterViewInit() {
this.routerOutlet.activateEvents
.pipe(
map(() => this.routerOutlet
.activatedRouteData
)
)
.subscribe((data) => {
// Code
});
}
<router-outlet #router="outlet"></router-outlet>
回答by sainu
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();
}

