离子日历事件未在设备上加载 [英] Ionic calendar event does not load on device

查看:57
本文介绍了离子日历事件未在设备上加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个日历事件应用程序,它在浏览器中运行完美,但是当我在设备上构建它时,日期格式却不同,并且显示了错误.我为此使用了ionic2-calendar,并且错误仅在它在浏览器上完美运行的真实设备上发生.

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.

这是我的home.page.ts

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


}

这是我的storage.service.ts

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);
  }


}

这是我的home.page.html

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.

这是错误消息,我已经使用ionic2-calendar了,并且错误仅发生在可以在浏览器上完美运行的真实设备上

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)

推荐答案

请记住,将数据存储后,将保留为字符串数据类型.
我在home.page.ts的loadItems()函数中看到它是从存储中取出的.
因此,您需要为存储中的每个记录循环.

Please keep in mind that after you put your data in storage, it will be kept as a string data type.
I saw that in your loadItems() function of home.page.ts, it took what it is from the storage.
So what you need to do is looping for each record in your storage.

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);
});

这篇关于离子日历事件未在设备上加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆