问题:在 ActivatedRoute 订阅数据对象时,永远不会检索在路由定义的静态数据。其他一切似乎工作正常,数据对象不为空,但我无法从中获取数据。当我尝试调试数据对象中的数据时,它输出“未定义”,当我尝试将它绑定(bind)到 UI 时,什么也没有显示,但是当我在 Chrome 中查看 ActivatedRoute 消息时,它有数据。经过多次尝试后,我很确定我的语法应该基于许多示例工作,所以 Angular 6 中是否发生了一些变化,或者 Angular 有什么问题?
路线代码:
const appRoutes: Routes = [
{
path: "article",
redirectTo: "/article/partners",
pathMatch: "full"
},
{
path: "article",
children: [
{
path: "bawo",
component: BawoArticleComponent,
data: { title: 'BaWo' }
},
{
path: "goldenhands",
component: GoldenHandsArticleComponent,
data: { title: 'Golden Hands' }
},
{
path: "investors",
component: InvestorsArticleComponent,
data: { title: 'Investors' }
},
{
path: "partners",
component: PartnersArticleComponent,
data: { title: 'Partners' }
}
]
},
{
path: "**",
redirectTo: "/article/partners"
}
];
检索组件代码(我在相关代码所在的地方注释了):
export class ArticleSelectorComponent implements OnInit {
arrowFader: string;
opacity: string;
fadeTimer: Observable<number>;
constructor(private router: Router, private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.router.events.subscribe((e: RouterEvent) => {
this.fadeTimer = timer(0, 150);
let subscription = this.fadeTimer.subscribe(currentValue => {
let calc = currentValue & 3;
if (calc == 0) {
this.arrowFader = '>';
this.opacity = '0.5';
}
else if (calc == 1) {
this.arrowFader = '>>';
this.opacity = '0.65';
}
else {
this.arrowFader = '>>>';
this.opacity = '0.8';
}
});
this.fadeTimer.subscribe(currentValue => {
if(currentValue >= 14) {
subscription.unsubscribe();
this.opacity = '1.0';
}
});
});
// THIS DOESN'T WORK!!!!
this.activatedRoute.data.subscribe((data: Data) => {
console.log(data['title']);
});
}
// not relevant, this code is ran with parameter at html buttons
navToArticle(num: number) {
let navStr = '';
switch(num){
case 1: {
navStr = '/article/bawo';
break;
}
case 2: {
navStr = '/article/goldenhands';
break;
}
case 3: {
navStr = '/article/partners';
break;
}
case 4: {
navStr = '/article/investors';
break;
}
}
this.router.navigateByUrl(navStr);
}
}
AppComponent 的 HTML 代码(带有组件指令):
<div class="site">
<div class="top">
<div class="anim-in-left">
<app-domains></app-domains>
</div>
<div class="anim-in-down top-title">
<h1 class="top-title-text">{{ topTitle }}</h1>
</div>
<div class="anim-in-right">
<app-presence></app-presence>
</div>
</div>
<div class="anim-in-up middle">
<app-article-selector></app-article-selector>
</div>
</div>
最佳答案
尝试下面的代码段,因为如果您立即订阅 activatedRoute,它只会订阅当前组件在路由器配置中注册的路由器数据更改,我刚刚添加了 NavigationEnd 过滤器,因此它不会被所有其他不需要的事件触发对于这个要求。
...
ngOnInit() {
...
this.title$ = this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(_ => this.activatedRoute),
map((route) => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
mergeMap((route) => route.data),
map((data) => data.title)
);
this.title$.subscribe(title => console.log(title));
...
}
...
关于Angular 6 - 无法检索静态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50912789/