Angular 4中获取今日、明日日期变量并用于HTTP请求的方法
在Angular 4中获取格式化的今日/明日日期并用于HTTP请求
我来帮你一步步实现这个需求,结合你给出的BookingService代码,咱们分两步走:先搞定日期的格式化,再把它们用到HTTP请求里。
1. 实现日期格式化并定义变量
原生Date对象直接输出的格式不符合yyyy-MM-dd要求,我们可以在服务里写一个简单的格式化方法(比依赖Angular的DatePipe更直接,避免额外配置),然后初始化今日和明日的日期变量。
修改你的BookingService代码如下:
import { Http } from '@angular/http'; import { Injectable } from '@angular/core'; import { KioskService } from './path-to-kiosk-service'; // 替换成你的KioskService实际路径 @Injectable() export class BookingService { private config: Object; public today: string; public tomorrow: string; public domainSettings: Object = {}; constructor( private http: Http, private kioskservice: KioskService ) { // 初始化今日日期并格式化 const currentDate = new Date(); this.today = this.formatDate(currentDate); // 计算明日日期并格式化 const nextDate = new Date(currentDate); nextDate.setDate(currentDate.getDate() + 1); // 日期加1得到明日 this.tomorrow = this.formatDate(nextDate); } // 私有工具方法:将Date对象转为yyyy-MM-dd格式字符串 private formatDate(date: Date): string { const year = date.getFullYear(); // 月份从0开始,需+1并补零到两位 const month = String(date.getMonth() + 1).padStart(2, '0'); // 日期补零到两位 const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } // ... 你的其他服务方法 }
如果你更倾向于用Angular自带的DatePipe,可以这样操作:
- 在你的模块(比如
AppModule)的providers数组中添加DatePipe - 在
BookingService构造函数中注入DatePipe,用它来格式化日期:
// 构造函数注入DatePipe constructor( private http: Http, private kioskservice: KioskService, private datePipe: DatePipe ) { const currentDate = new Date(); this.today = this.datePipe.transform(currentDate, 'yyyy-MM-dd'); const nextDate = new Date(currentDate); nextDate.setDate(currentDate.getDate() + 1); this.tomorrow = this.datePipe.transform(nextDate, 'yyyy-MM-dd'); }
2. 在HTTP请求中使用日期变量
现在today和tomorrow已经是符合要求的字符串了,你可以把它们作为请求参数、请求体的一部分来使用,这里举两个常见场景:
示例1:作为GET请求的查询参数
getDailyBookings() { const params = new URLSearchParams(); params.set('today', this.today); params.set('tomorrow', this.tomorrow); return this.http.get('/api/bookings', { search: params }) .map(response => response.json()); }
示例2:作为POST请求的请求体字段
submitBooking(bookingInfo: any) { // 把日期变量合并到请求体中 const requestBody = { ...bookingInfo, bookingStartDate: this.today, bookingEndDate: this.tomorrow }; return this.http.post('/api/bookings', requestBody) .map(response => response.json()); }
这样就能把格式化后的今日、明日日期顺利传递给后端啦~
内容的提问来源于stack exchange,提问作者user7705439
相关产品推荐
相关产品推荐

