1
我有一个到广播节目时间表的路由设置,我传递给ScheduleComponent
的参数是日期。不过,我在尝试为路线设置默认值时遇到了问题。如何在Angular2中为广播时间表设置默认日期url参数
经过很多失败后,我决定在链接上始终设置日期。但是现在我需要突出显示.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$);
}
我不知道如果我理解正确的,但不你基本上想要日期参数是可选的?如果提供参数,则使用该日期('/ schedule/2017-06-17')。如果没有提供('/ schedule'),只需在组件本身设置日期?如果是这种情况,你可以简单地使用相同的组件2条路线。 ('/ schedule /:date'和'/ schedule')。如果我的理解错误,请纠正我,我会尽力提供一个真实的答案。 –