加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:35:31 所属栏目:安全 来源:网络整理
导读:我正在使用router.event.subscribe @ angular / router来查看url更改以执行if语句尽管event.subscribe工作正常.但我的问题是如何避免重复我的if语句只是为了在这些网址上显示标题.它可能不是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'
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读