edit.page.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { Component } from '@angular/core';
  2. import { ModalController } from '@ionic/angular';
  3. import { CloudObject, CloudUser } from 'src/lib/ncloud';
  4. @Component({
  5. selector: 'app-edit',
  6. templateUrl: './edit.page.html',
  7. styleUrls: ['./edit.page.scss'],
  8. standalone:false,
  9. })
  10. export class EditPage {
  11. diary: any = {
  12. Did: 0,
  13. date: this.getCurrentDate(),
  14. weekday: this.getCurrentWeekday(),
  15. time: this.getCurrentTime(),
  16. content: '',
  17. weather: '',
  18. mood: '',
  19. user: '' // 添加用户字段
  20. };
  21. currentUser: CloudUser | null = null;
  22. constructor(private modalCtrl: ModalController) {}
  23. ngOnInit() {
  24. // 生成随机ID
  25. this.diary.Did = Math.floor(Math.random() * 100000);
  26. // 设置当前用户
  27. if (this.currentUser) {
  28. this.diary.user = this.currentUser.toPointer();
  29. }
  30. }
  31. // 获取当前日期
  32. private getCurrentDate(): string {
  33. //return new Date().getDate().toString();
  34. const now = new Date();
  35. return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
  36. }
  37. // 获取当前星期
  38. private getCurrentWeekday(): string {
  39. const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  40. return weekdays[new Date().getDay()];
  41. }
  42. // 获取当前时间
  43. private getCurrentTime(): string {
  44. const now = new Date();
  45. return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
  46. }
  47. async saveDiary() {
  48. if (!this.diary.user) {
  49. console.error('用户未登录,无法保存日记');
  50. this.modalCtrl.dismiss({ saved: false });
  51. return;
  52. }
  53. // 创建新的日记对象
  54. const newDiary = new CloudObject("Diary");
  55. newDiary.set(this.diary);
  56. try {
  57. await newDiary.save();
  58. // 保存成功,返回并刷新列表
  59. this.modalCtrl.dismiss({ saved: true });
  60. } catch (error) {
  61. console.error('保存日记失败:', error);
  62. this.modalCtrl.dismiss({ saved: false });
  63. }
  64. }
  65. // 关闭模态框
  66. dismiss() {
  67. this.modalCtrl.dismiss({ saved: false });
  68. }
  69. }