gpt4 book ai didi

angular - ActivatedRoute 不会在路线更改时更新子路线数据

转载 作者:行者123 更新时间:2023-12-04 02:42:31 26 4
gpt4 key购买 nike

我正在尝试使用 ActivatedRoute 从父组件获取子路由数据('layout') .我已经尝试了以下示例,并且能够获得我正在寻找的数据,但只能获得一次。在子路由更改期间,我没有看到更新的“布局”值。

路线

const routes: Routes = [
{
path: '',
component: Layout1Component,
children: [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
loadChildren: './pages/analytics/analytics.module#AnalyticsModule',
data: {
layout: 'boxed'
}
},
{
path: 'files',
loadChildren: './pages/files/files.module#FilesModule',
data: {
layout: 'full'
}
}
]
}
];

Layout1Component
export class Layout1Component implements OnInit {
constructor(private service: AppService, route: ActivatedRoute) {
this.layout = route.snapshot.firstChild.data['layout'];

route.url.subscribe(() => {
console.log(route.snapshot.firstChild.data['layout']);
});
}
}

我希望每次更改路线时都使用更新的“布局”值打印 console.log。

请帮我解决这个问题。

最佳答案

根据我的理解,您只获取一次数据的原因是因为 ActivatedRoute获取 url作为 行为主题 当它被实例化时。

function createActivatedRoute(c: ActivatedRouteSnapshot) {
return new ActivatedRoute(
new BehaviorSubject(c.url), new BehaviorSubject(c.params), new BehaviorSubject(c.queryParams),
new BehaviorSubject(c.fragment), new BehaviorSubject(c.data), c.outlet, c.component, c);
}

Here's the link for the above snippet

这意味着当您订阅时,您只会获得第一个存储的值。

解决它的一种方法是使用 路由器事件 .

假设你有这样的事情:

const routes: Route[] = [
{
path: '',
component: HelloComponent,
children: [
{
path: 'foo',
loadChildren: () => import('path/to/foo').then(m => m.FooModule),
data: {
name: 'andrei'
}
},
{
path: 'bar',
loadChildren: () => import('path/to/bar').then(m => m.BarModule),
data: {
name: 'john'
}
},
]
},
]

这是一个可能的解决方案:

 constructor (private router: Router, private route: ActivatedRoute) { }

ngOnInit () {
const routeEndEvent$ = this.router.events
.pipe(
filter(e => e instanceof NavigationEnd),
tap(() => console.warn("END")),
);

this.router.events
.pipe(
filter(e => e instanceof ChildActivationEnd && e.snapshot.component === this.route.component),
buffer(routeEndEvent$),
map(([ev]) => (ev as ChildActivationEnd).snapshot.firstChild.data),
takeUntil(this.ngUnsubscribe$)
)
.subscribe(childRoute => {
console.log('childRoute', childRoute);
})
}
  • routeEndEvent$是一个 observable,只有在路由准备好时才会发出 ( NavigationEnd )
  • filter(e => e instanceof ChildActivationEnd && e.snapshot.component === this.route.component) :在检查了路由器发出的事件一段时间后,我达到了这个解决方案,以确定组件( HelloComponent )是否是更改的路由( this.route.component )的父级( e.snapshot.component )。
  • buffer(routeEndEvent$) :我们只想在路由器达到其最终状态( NavigationEnd )时采取行动。 here您可以阅读有关 buffer 的更多信息运算符(operator)

  • StackBlitz

    关于angular - ActivatedRoute 不会在路线更改时更新子路线数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58681856/

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