post-create.page.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import { Component } from '@angular/core';
  2. import { NavController, AlertController } from '@ionic/angular';
  3. import Parse from 'parse';
  4. @Component({
  5. selector: 'app-post-create',
  6. templateUrl: './post-create.page.html',
  7. styleUrls: ['./post-create.page.scss'],
  8. })
  9. export class PostCreatePage {
  10. title: string = '';
  11. content: string = '';
  12. image: string = '';
  13. constructor(private navCtrl: NavController, private alertCtrl: AlertController) {}
  14. async uploadImage() {
  15. // 实现上传图片的逻辑
  16. const alert = await this.alertCtrl.create({
  17. header: '上传图片',
  18. inputs: [
  19. {
  20. name: 'imageUrl',
  21. type: 'url',
  22. placeholder: '输入图片URL'
  23. }
  24. ],
  25. buttons: [
  26. {
  27. text: '取消',
  28. role: 'cancel'
  29. },
  30. {
  31. text: '上传',
  32. handler: (data) => {
  33. this.image = data.imageUrl;
  34. }
  35. }
  36. ]
  37. });
  38. await alert.present();
  39. }
  40. async submitPost() {
  41. if (!this.title || !this.content) {
  42. const alert = await this.alertCtrl.create({
  43. header: '错误',
  44. message: '标题和正文不能为空',
  45. buttons: ['确定']
  46. });
  47. await alert.present();
  48. return;
  49. }
  50. const currentUser = Parse.User.current();
  51. if (!currentUser) {
  52. const alert = await this.alertCtrl.create({
  53. header: '错误',
  54. message: '请先登录',
  55. buttons: ['确定']
  56. });
  57. await alert.present();
  58. return;
  59. }
  60. // 获取用户的 username 和 avatarUrl
  61. const authorInfo = {
  62. username: currentUser.get('username'),
  63. avatarUrl: currentUser.get('avatarUrl') || 'assets/images/default-avatar.jpg' // 默认头像路径
  64. };
  65. const Post240709 = Parse.Object.extend('Post240709');
  66. const post = new Post240709();
  67. post.set('title', this.title);
  68. post.set('content', this.content);
  69. post.set('imageUrl', this.image);
  70. post.set('author', authorInfo); // 设置 author 字段为包含 username 和 avatarUrl 的对象
  71. try {
  72. const savedPost = await post.save();
  73. const successAlert = await this.alertCtrl.create({
  74. header: '成功',
  75. message: '发布成功',
  76. buttons: ['确认']
  77. });
  78. await successAlert.present();
  79. // // 延迟一段时间后返回首页
  80. // setTimeout(() => {
  81. // this.navCtrl.navigateBack('/home');
  82. // }, 1000); // 1秒后返回首页,可以根据需求调整延迟时间
  83. } catch (error) {
  84. console.error('Error while creating post:', error);
  85. const alert = await this.alertCtrl.create({
  86. header: '错误',
  87. message: '发布失败,请重试',
  88. buttons: ['确定']
  89. });
  90. await alert.present();
  91. }
  92. }
  93. }