在我现在的情况下,我将
data object
放入延迟加载组件中,我想获取 data
内容并显示在 html 中。但我做不到。这是脚本:
const routes: Routes = [
{
path: '',
component: CancellationComponent,
data: {
animation: 'cancellation',
title: 'Cancelamento de contratos'
},
resolve: {
data: CancellationResolveService
}
}
];
组件由
Lazy Load
加载。
我想要的是,当我直接在#/cancellation
访问时,我想得到data content
,最好的方法是什么?任何想法?非常感谢!
您可以从快照中访问路线的数据属性,如下所示:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
templateUrl: './app/home/welcome.component.html'
})
export class WelcomeComponent implements OnInit {
public pageTitle: string;
constructor( private route: ActivatedRoute) {
}
ngOnInit(): void {
this.pageTitle = this.route.snapshot.data['title'];
}
}
这需要注入ActivatedRoute,然后访问路由的快照。您可以使用快照而不是订阅,因为数据是静态的。
希望这有帮助。
取决于您想在哪里使用它, 但如果升高了,你可以尝试:
constructor(private router: Router,
private activatedRoute: ActivatedRoute)
您将检测每一次路线的变化并获取路线中的数据。
router.events.pipe(
filter(event => event instanceof NavigationEnd), // Only get the event of NavigationEnd
map(() => activatedRoute), // Listen to activateRoute
map(route => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
filter(route => route.outlet === 'primary'),
mergeMap(route => route.data) // get the data
)
以 rxjs 流形式获取当前路由数据的另一种方法是:
constructor(router: Router) {
const routeData$ = router.events.pipe(
filter(e => e instanceof ActivationEnd),
throttleTime(0),
map((e: ActivationEnd) => e.snapshot.data)
);
}
使用 DI 获取路由器服务。
管道路由事件并过滤激活结束事件(我们可以在那里获取路由快照并获取数据属性)
限制当前堆栈的事件。如果我们有嵌套路由,则事件将被从最底部的路由触发到顶部,并且我们只需要第一个(即当前的),因此节流阀将获得第一个 ActivationEnd 事件,并将其推送到流中并过滤掉休息当前导航。
然后我们从当前快照中获取数据
在订阅内(无论在哪里),您将获得当前路线的数据。
此外,如果我们想将不同路线的不同 ActivationEnd 事件的所有数据合并到一个对象中,我们也可以这样做:
constructor(router: Router) {
router.events.pipe(
filter(e => e instanceof ActivationEnd),
buffer(router.events.pipe(filter(e => e instanceof NavigationEnd), debounceTime(0))),
map((events: ActivationEnd[]) => events.reduce((acc, curr) => ({ ...acc, ...curr.snapshot.data }), {}))
);
}
筛选出 ActivationEnd 事件(我们在那里有路线快照,因此我们可以从中获取各个路线的数据)
缓冲它们,直到我们获得当前堆栈的所有 NavigationEnd 事件
减少所有缓冲事件并收集一个对象内的数据(不处理碰撞)
或者使用第一个解决方案与 paramsInheritanceStrategy
ActivatedRoute具有数据属性
试试这个代码
this.router.getCurrentNavigation()
this.router.getCurrentNavigation().extras.state 将具有状态参数