gpt4 book ai didi

javascript - Angular 2 ActivatedRoute返回空

转载 作者:太空狗 更新时间:2023-10-29 17:58:36 25 4
gpt4 key购买 nike

我正在尝试获取一个字符串,它会告诉我用于访问该页面的 url - 例如,如果有人导航到 localhost/messages/inbox,我希望路由的“消息”部分作为一个字符串.

到目前为止,我用来执行此操作的代码是:

    import { Router, RouterModule, ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-sub-nav',
templateUrl: './sub-nav.component.html',
styleUrls: ['./sub-nav.component.css']
})
export class SubNavComponent implements OnInit {

constructor(private router: ActivatedRoute) { }

ngOnInit() {

console.log(this.router.snapshot);

}
}

当我查看控制台时,它返回整个 ActivatedRoute 对象,但大部分属性都是空的。包括快照、 child 、 parent 等。有什么我想念的吗?

只是一个简短的说明 - 我需要在每次路线更改时更新此字符串。我之前确实使用 Router 对象进行过此操作,但每次路由更改时它似乎都保持静态。

最佳答案

Just a quick note - I need this string to update each time the route changes. I did have this working previously with the Router object, but this appears to remain static each time the route changes.

订阅 Router NavigationEnd 事件。

NavigationEnd - 表示导航成功结束时触发的事件

 ngOnInit() {
this.router.events.subscribe(events => {
if (events instanceof NavigationEnd) {
console.log('NavigationEnd evnet', events);
}
})
}

因此,每次成功导航到路由时,都会使用事件对象触发此事件:

{
urlAfterRedirects: string
toString(): string
// inherited from router/RouterEvent
id: number
url: string
}

StackBlitz EXAMPLE

关于javascript - Angular 2 ActivatedRoute返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49603533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com