angularjs – angular2使用router.subscribe来观看网址更改

前端之家收集整理的这篇文章主要介绍了angularjs – angular2使用router.subscribe来观看网址更改前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用router.event.subscribe @ angular / router来查看url更改以执行if语句尽管event.subscribe工作正常.但我的问题是如何避免重复我的if语句只是为了在这些网址上显示标题.它可能不是router.subscribe,但不知道该用什么.

基本上想要一个基于你所在网址的动态标题.

this._router.events.subscribe((event) => {
            console.log('route changed');
            if(this.location.path() == '/1'){
                this.title = 'Title 1';
            } else if(this.location.path() == '/2'){
                this.title = 'Title 2';
            }
        });

我不知道这是否有意义.我可以改变我的route.ts路径以获得类似{path:’Title-1′}的东西,然后通过执行.replace()删除 – 但这样做会给我www.mysite.com/Title-1但它不会看起来很友好.

解决方法

这是我的方法,它工作正常,特别是对于嵌套路由:

我使用递归辅助方法在路由更改后获取最深的可用标题

@Component({
  selector: 'app',template: `
    <h1>{{title}}</h1>
    <router-outlet></router-outlet>
  `
})
export class AppComponent implements OnInit {
  constructor(private router: Router) {}

  title: string;

  private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) {
    var title = routeSnapshot.data ? routeSnapshot.data['title'] : '';
    if (routeSnapshot.firstChild) {
      title = this.getDeepestTitle(routeSnapshot.firstChild) || title;
    }
    return title;
  }

  ngOnInit() {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.title = this.getDeepestTitle(this.router.routerState.snapshot.root);
      }
    });
  }
}

这是假设您已在路径的data属性中分配了页面标题,如下所示:

{
  path: 'example',component: ExampleComponent,data: {
    title: 'Some Page'
  }
}

猜你在找的Angularjs相关文章