Ionic calendar event does not load on device

好久不见. 提交于 2020-02-06 12:50:41

问题


I am doing a calendar event application and it runs perfect in a browser but when I build it on a device the date format is different and it is showing me errors. I have used ionic2-calendar for this and the error is happening only on a real device it runs perfectly on a browser.

I have tried everything but I can't solve this problem.

This is my 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();
}


}

this is my 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);
  }


}

this is my 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>

It works perfect on my browser this only happens in my device.

This is the error message, I have used ionic2-calendar for this and the error is happening only on a real device it runs perfectly on a browser

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)

来源:https://stackoverflow.com/questions/56214875/ionic-calendar-event-does-not-load-on-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!