我有一个设置为广播节目时间表的路线,我传递给ScheduleComponent
的参数是日期。但是,我在尝试为路线设置默认值时遇到问题。
经过多次失败后,我决定始终在链接上设置日期。但现在我需要突出显示.active
路由,因此需要弄清楚如何设置计划的默认值。
有人可以帮助我指出正确的方向。
当前路线:
const routes = [
{
path: 'schedule/:date',
component: ScheduleComponent,
}
]
我正在考虑做这样的事情,但是不能安排在给定日期前往正确的地方。我不确定这是正确的方法:
const routes = [
{
path: 'schedule',
component: ScheduleComponent,
redirectTo: 'schedule/yyyy-MM-dd', // Replacing yyyy-MM-dd with todays date.
children: [
{ path: ':date', component: ScheduleComponent, pathMatch: 'full' }
]
}
]
主导航构造函数,这是我想要使用/schedule
:
constructor(private datePipe: DatePipe, private colorService: ColorService) {
this.navs = [
{url: '/schedule/' + this.datePipe.transform(new Date(), "yyyy-MM-dd"), content: "Schedule"},
// ... other routes
];
示例链接:
<a [routerLink]="['/schedule', day | date: 'yyyy-MM-dd']"
routerLinkActive="active"
class="schedule-nav-button">
{{day | date:"EEE"}}
</a>
日程安排组件:
import {Component, OnInit, Inject} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {Http} from "@angular/http";
import "rxjs/add/operator/map"
import "rxjs/add/operator/switchMap"
import {BehaviorSubject} from "rxjs/BehaviorSubject";
import {ColorService} from "../../services/color.service";
@Component({
selector: 'app-schedule',
templateUrl: '../views/schedule.component.html',
styleUrls: ['../css/schedule.component.css']
})
export class ScheduleComponent implements OnInit {
schedule$ = new BehaviorSubject([{
"start_time": new Date(),
"end_time": new Date(),
"radio_show": {
"id": 0,
"name": "Loading...",
"description": "",
"small_thumb": "",
"presenters": [
{
id: 0,
name: "Loading.."
}
]
}
},]);
date: Date;
constructor(@Inject('api') private api, private colorService: ColorService, private route: ActivatedRoute, private http: Http) {
this.date = new Date();
route.params
.map((p: any) => p.date)
.switchMap(date => http.get(api + '/schedules/' + date)
.map(res => res.json())
).subscribe(this.schedule$);
}
ngOnInit() {
this.colorService.change("blue");
}
}
更新
这是我的解决方案。正如Thomas Schoutsens建议我将我的路线设置为指向相同的组件。
const routes = [
{ path: 'schedule/:date', component: ScheduleComponent },
{ path: 'schedule', component: ScheduleComponent }
]
然后我添加了一个或语句来添加默认日期,如果没有提供(date || this.datePipe.transform(this.date, "yyyy-MM-dd"))
。
constructor(@Inject('api') private api, private datePipe: DatePipe, private colorService: ColorService, private route: ActivatedRoute, private http: Http) {
this.date = new Date();
route.params
.map((p: any) => p.date)
.switchMap(date => http.get(api + '/schedules/' + (date || this.datePipe.transform(this.date, "yyyy-MM-dd")))
.map(res => res.json())
).subscribe(this.schedule$);
}
答案 0 :(得分:9)
不要在今天的日期使用默认参数,而是将参数设为可选参数,并在需要时在组件中设置默认日期。
要使参数可选,请使用相同的组件创建2个路径:
const routes = [
{ path: 'schedule/:date', component: ScheduleComponent },
{ path: 'schedule', component: ScheduleComponent }
]
然后在你的组件中:
route.params.subscribe(params => {
this.date = params['date'];
if(!date)
this.date = new Date();
});