use*_*867 9 javascript angular-routing angular
我在我的应用程序路由模块中定义了一些路由数据,如下所示:
const appRoutes:Routes = [
{path: '', component: LoginComponent, data:[{PageName:"Login Page"}]}]
Run Code Online (Sandbox Code Playgroud)
我想全局获取数据,所以我使用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
}
Run Code Online (Sandbox Code Playgroud)
我尝试注入ActivatedRoute,但每次重定向后都没有更新.
无论如何,我可以在哪里配置页面名称并在全球范围内获取它app.component.ts.
Hri*_*mov 20
尝试filter并循环播放您的活动而不是subscribe
constructor(router:Router, route:ActivatedRoute) {
router.events
.filter(e => e instanceof NavigationEnd)
.forEach(e => {
this.title = route.root.firstChild.snapshot.data['PageName'];
});
}
Run Code Online (Sandbox Code Playgroud)
请查看以下工作演示:https://plnkr.co/edit/rBToHRaukDlrSKcLGavh?p = info
dan*_*y74 15
此代码由 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)
)
}
Run Code Online (Sandbox Code Playgroud)
请参阅:https : //ultimatecourses.com/blog/dynamic-page-titles-angular-2-router-events
在他的示例中,他使用路由数据在应用程序组件中设置页面标题。
为什么访问父级中的路由数据如此复杂,我永远不会知道!
Pab*_*blo 13
如果您使用如下所示的Router对象静态路由:
{path:'',pathMatch:'full',component:NameComponent,data:{variableName:'variableValue'}},
在ngOnInit()上,您可以使用ActivatedRoute对象来恢复从路由器定义传递的数据:
ngOnInit(){this.localVariable = this.route.snapshot.data ['variableName']; }
Obs:我正在使用Angular 5!
| 归档时间: |
|
| 查看次数: |
23756 次 |
| 最近记录: |