我正在做一个日历事件应用程序,它在浏览器中运行完美,但是当我在设备上构建它时,日期格式却不同,并且显示了错误。我为此使用了ionic2-calendar,并且该错误仅在它在浏览器上完美运行的真实设备上发生。
我已经尝试了一切,但无法解决此问题。
这是我的home.page.ts
import { CalendarComponent } from 'ionic2-calendar/calendar';
import { Component, ViewChild, OnInit, Inject, LOCALE_ID } from '@angular/core';
import { Platform, ToastController, AlertController } from '@ionic/angular';
import { formatDate } from '@angular/common';
import { LocalNotifications, ELocalNotificationTriggerUnit, ILocalNotificationActionType, ILocalNotification } from '@ionic-native/local-notifications/ngx';
import { Storage } from '@ionic/storage';
import { StorageService, Item } from '../services/storage.service';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
scheduled = [];
event = {
startTime: '',
endTime: '',
setreminder: false,
title: '',
};
minDate = new Date().toISOString();
eventSource = [];
viewTitle;
calendar = {
mode: 'month',
currentDate: new Date(),
};
items: Item[] = [];
newItem: Item = <Item>{};
@ViewChild(CalendarComponent) myCal: CalendarComponent;
constructor(private plt: Platform,
private localNotifications: LocalNotifications,
private toastController: ToastController,
private storage: Storage,
private storageService: StorageService,
private alertCtrl: AlertController, @Inject(LOCALE_ID) private locale: string) {
this.plt.ready().then(() => {
this.loadItems();
this.localNotifications.on('click').subscribe(res => {
let msg = res.data ? res.data.mydata : '';
this.showAlert(res.title, res.text, msg);
});
this.localNotifications.on('trigger').subscribe(res => {
let msg = res.data ? res.data.mydata : '';
this.showAlert(res.title, res.text, msg);
});
});
}
ngOnInit() {
this.resetEvent();
}
resetEvent() {
this.event = {
startTime: new Date().toISOString(),
endTime: new Date().toISOString(),
setreminder: false,
title: '',
};
}
addEvent() {
let eventCopy = {
title: this.event.title,
startTime: new Date(this.event.startTime),
endTime: new Date(this.event.startTime),
};
let eventss = this.eventSource;
eventss.push(eventCopy);
this.eventSource = [];
this.eventSource = eventss;
this.myCal.loadEvents();
console.log(eventss);
this.storageService.addItem(eventCopy).then(item => {
eventCopy = <Item>{};
this.showToast('Event Added!');
this.loadItems();
});
}
loadItems() {
this.storageService.getItems().then(items => {
this.items = items;
if (items) {
this.eventSource = items;
}
else{
console.log('No events Yet');
}
console.log(this.eventSource);
});
}
getStorage(){
this.storage.get('name').then((val) => {
return ['name'];
});
}
// Change current month/week/day
next() {
var swiper = document.querySelector('.swiper-container')['swiper'];
swiper.slideNext();
}
back() {
var swiper = document.querySelector('.swiper-container')['swiper'];
swiper.slidePrev();
}
// Change between month/week/day
changeMode(mode) {
this.calendar.mode = mode;
}
// Focus today
today() {
this.calendar.currentDate = new Date();
}
// Selected date reange and hence title changed
onViewTitleChanged(title) {
this.viewTitle = title;
}
// Calendar event was clicked
async onEventSelected(event) {
// Use Angular date pipe for conversion
let start = formatDate(event.startTime, 'medium', this.locale);
let end = formatDate(event.endTime, 'medium', this.locale);
const alert = await this.alertCtrl.create({
header: 'Check your ajenda please',
// subHeader: event.desc,
message: 'From: ' + start + '<br><br>To: ' + end,
buttons: ['OK']
});
alert.present();
}
// Time slot was clicked
onTimeSelected(ev) {
let selected = new Date(ev.selectedTime);
this.event.startTime = selected.toISOString();
selected.setHours(selected.getHours() + 1);
this.event.endTime = (selected.toISOString());
}
// scheduleNotification() {
// this.localNotifications.schedule({
// id: 1,
// title: 'Agenda Reminder',
// text: 'Please Check Your Agenda',
// data: { mydata: 'Please Check your agenda on ' + new Date(this.event.startTime) },
// trigger: { at: new Date(new Date(this.event.startTime)) }
// });}
showAlert(header, sub, msg) {
this.alertCtrl.create({
header: header,
subHeader: sub,
message: msg,
buttons: ['Ok']
}).then(alert => alert.present());
}
async showToast(msg) {
const toast = await this.toastController.create({
message: msg,
duration: 2000
});
toast.present();
}
}
这是我的storage.service.ts
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
export interface Item {
// title: string,
startTime: Date,
endTime: Date,
// reminder: Date,
}
const ITEMS_KEY = 'my-items';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor(private storage: Storage) { }
// CREATE
addItem(item: Item): Promise<any> {
return this.storage.get(ITEMS_KEY).then((items: Item[]) => {
if (items) {
items.push(item);
return this.storage.set(ITEMS_KEY, items);
} else {
return this.storage.set(ITEMS_KEY, [item]);
}
});
}
// READ
getItems(): Promise<Item[]> {
return this.storage.get(ITEMS_KEY);
}
}
这是我的home.page.html
<ion-header>
<ion-toolbar color="primary">
<ion-title>
{{ viewTitle }}
</ion-title>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-buttons slot="end">
<ion-button (click)="today()">Today</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="bg-style">
<!-- Card for adding a new event -->
<ion-card class="bg-card">
<ion-card-header tappable (click)="collapseCard = !collapseCard">
<ion-card-title class="font-color">Add Reminder</ion-card-title>
</ion-card-header>
<ion-card-content *ngIf="!collapseCard">
<ion-item>
<ion-label>Set Time</ion-label>
<ion-datetime displayFormat="MM/DD/YYYY h:mm" pickerFormat="MMM D:h:mm" [(ngModel)]="event.startTime" ></ion-datetime>
</ion-item>
<ion-button expand="block" (click)="addEvent()">Add Event</ion-button>
</ion-card-content>
</ion-card>
<ion-row>
<ion-col size="4">
<ion-button expand="block" [color]="calendar.mode == 'month' ? 'primary' : 'secondary'" (click)="changeMode('month')">Month</ion-button>
</ion-col>
<ion-col size="4">
<ion-button expand="block" [color]="calendar.mode == 'week' ? 'primary' : 'secondary'" (click)="changeMode('week')">Week</ion-button>
</ion-col>
<ion-col size="4">
<ion-button expand="block" [color]="calendar.mode == 'day' ? 'primary' : 'secondary'" (click)="changeMode('day')">Day</ion-button>
</ion-col>
<!-- Move back one screen of the slides -->
<ion-col size="6" text-left>
<ion-button fill="clear" (click)="back()">
<ion-icon name="arrow-back" slot="icon-only"></ion-icon>
</ion-button>
</ion-col>
<!-- Move forward one screen of the slides -->
<ion-col size="6" text-right>
<ion-button fill="clear" (click)="next()">
<ion-icon name="arrow-forward" slot="icon-only"></ion-icon>
</ion-button>
</ion-col>
</ion-row>
<calendar
[eventSource]="eventSource"
[calendarMode]="calendar.mode"
[currentDate]="calendar.currentDate"
(onEventSelected)="onEventSelected($event)"
(onTitleChanged)="onViewTitleChanged($event)"
(onTimeSelected)="onTimeSelected($event)"
startHour="6"
endHour="20"
step="30"
startingDayWeek="1">
</calendar>
<ion-item *ngFor="let item of items">
<label> {{item.startTime}}</label>
<!-- <label> {{item.endTime}}</label> -->
</ion-item>
</ion-content>
它可以在我的浏览器上完美运行,这只会在我的设备上发生。
这是错误消息,我已经使用ionic2-calendar了,并且该错误仅发生在可以在浏览器上完美运行的真实设备上
ng:///NgCalendarModule/CalendarComponent.ngfactory.js:266 ERROR TypeError: event_1.startTime.getTime is not a function
at MonthViewComponent.push…/node_modules/ionic2-calendar/monthview.js.MonthViewComponent.onDataLoaded (/src-app-home-home-module.js:1423)
at MonthViewComponent.push…/node_modules/ionic2-calendar/monthview.js.MonthViewComponent.ngOnChanges (/src-app-home-home-module.js:1272)
at checkAndUpdateDirectiveDynamic (vendor.js:56161)
at checkAndUpdateNodeDynamic (vendor.js:57422)
at checkAndUpdateNode (vendor.js:57371)
at debugCheckAndUpdateNode (vendor.js:58002)
at debugCheckDirectivesFn (vendor.js:57962)
at Object.eval [as updateDirectives] (ng:///NgCalendarModule/CalendarComponent.ngfactory.js:323)
at Object.debugUpdateDirectives [as updateDirectives] (vendor.js:57954)
at checkAndUpdateView (vendor.js:57350)
答案 0 :(得分:0)
请记住,将数据放入存储区后,它会保留为字符串数据类型。
我在 home.page.ts 的 loadItems() 函数中看到,它从存储中取出了它的内容。
因此,您需要做的是对存储中的每条记录进行循环。
loadItems() {
this.storageService.getItems().then(items => {
this.items = items;
if (items) {
let itemss = [];
items.forEach((item, idx) => {
let evtCopy = {
title: item.title,
startTime: new Date(item.startTime),
endTime: new Date(item.startTime),
};
itemss.push(evtCopy);
});
this.eventSource = itemss;
} else {
console.log('No events Yet');
}
console.log(this.eventSource);
});