【发布时间】:2018-06-18 15:24:49
【问题描述】:
问题:在路由中定义的静态数据永远不会通过在 ActivatedRoute 订阅数据对象来检索。其他一切似乎都工作正常,数据对象不为空,但我无法从中获取数据。当我尝试从数据对象中调试数据时,它输出“未定义”,当我尝试将其绑定到 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>
【问题讨论】:
-
这个 ArticleSelectorComponent 在您的路由器中链接到哪里?还是纯组件?
-
控制台有错误吗?
-
@AbineshDevadas 它是 AppComponent 中的一个组件指令
-
@FranklinPious 他们以前出现过,但似乎已经消失了
-
根据文档尝试访问内部构造函数 - angular.io/api/router/ActivatedRoute
标签: angular typescript angular-routing