0225304 преди 6 дни
родител
ревизия
2513335d26

+ 40 - 30
myapp/src/app/services/auth.service.ts

@@ -7,67 +7,77 @@ import { Router } from '@angular/router';
   providedIn: 'root'
 })
 export class AuthService {
-  private currentUser: CloudUser | null = null;
+  private _currentUser: CloudUser | null = null;
 
   constructor(private router: Router) {
     this.initializeUser();
   }
 
-  private initializeUser() {
-    this.currentUser = new CloudUser();
+  private async initializeUser() {
+    this._currentUser = new CloudUser();
+    try {
+      await this._currentUser.current(); // 尝试获取当前用户
+    } catch (error) {
+      console.log('No logged in user');
+    }
+  }
+
+  get currentUser(): CloudUser | null {
+    return this._currentUser;
   }
 
-  // 获取当前用户
-  async getCurrentUser() {
-    if (!this.currentUser) {
-      this.initializeUser();
+  async getCurrentUser(): Promise<CloudUser | null> {
+    if (!this._currentUser) {
+      await this.initializeUser();
     }
-    return await this.currentUser?.current();
+    return this._currentUser;
   }
 
-  // 用户登录
   async login(username: string, password: string): Promise<boolean> {
+    if (!this._currentUser) {
+      await this.initializeUser();
+    }
+    
     try {
-      const user = await this.currentUser?.login(username, password);
-      if (user) {
-        return true;
-      }
-      return false;
+      const user = await this._currentUser?.login(username, password);
+      return !!user;
     } catch (error) {
-      console.error('登录失败:', error);
+      console.error('Login failed:', error);
       return false;
     }
   }
 
-  // 用户注册
   async register(username: string, password: string, email?: string): Promise<boolean> {
     try {
+      const newUser = new CloudUser();
       const additionalData = email ? { email } : {};
-      const user = await this.currentUser?.signUp(username, password, additionalData);
-      return !!user;
+      const user = await newUser.signUp(username, password, additionalData);
+      
+      if (user) {
+        this._currentUser = user;
+        return true;
+      }
+      return false;
     } catch (error) {
-      console.error('注册失败:', error);
+      console.error('Registration failed:', error);
       return false;
     }
   }
 
-  // 用户登出
   async logout(): Promise<boolean> {
+    if (!this._currentUser) return true;
+    
     try {
-      const success = await this.currentUser?.logout();
-      if (success) {
-        this.currentUser = null;
-        this.router.navigate(['/login']);
-      }
-      return !!success;
+      const success = await this._currentUser.logout();
+      this._currentUser = null;
+      return success ?? true; // 如果 success 是 undefined,则返回 true
     } catch (error) {
-      console.error('登出失败:', error);
+      console.error('Logout failed:', error);
       return false;
     }
-  }
+}
 
-  // 检查是否已登录
   isAuthenticated(): boolean {
-    return !!this.currentUser?.sessionToken;
+    return !!this._currentUser?.sessionToken;
   }
 }

+ 1 - 3
myapp/src/app/tab1/edit/edit.page.ts

@@ -16,7 +16,7 @@ export class EditPage {
     time: this.getCurrentTime(),
     content: '',
     weather: '',
-    mood: ''
+    mood: '',
   };
 
   constructor(private modalCtrl: ModalController) {}
@@ -46,8 +46,6 @@ export class EditPage {
   async saveDiary() {
     // 创建新的日记对象
     const newDiary = new CloudObject("Diary");
-    //newDiary.equalTo('user',Parse.User.current()?.id);
-    //const currentUser = Parse.User.current();
     newDiary.set(this.diary);
     
     try {

+ 0 - 3
myapp/src/app/tab1/tab1.page.html

@@ -11,9 +11,6 @@
         <ion-button (click)="goToEditPage('编辑')">
             <ion-icon name="add"></ion-icon>
         </ion-button>
-        <!-- <ion-button (click)="importDiary()">
-        <ion-icon name="cloud-outline"></ion-icon>
-        </ion-button> -->
     </ion-buttons>
     </div>
 

+ 3 - 119
myapp/src/app/tab1/tab1.page.ts

@@ -4,7 +4,7 @@ import { ModalController } from '@ionic/angular';
 import { EditPage } from './edit/edit.page'; 
 import { IonRouterOutlet } from '@ionic/angular';
 import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
-import { ActivatedRoute } from '@angular/router'
+import { ActivatedRoute } from '@angular/router';
 @Component({
   selector: 'app-tab1',
   templateUrl: 'tab1.page.html',
@@ -13,9 +13,7 @@ import { ActivatedRoute } from '@angular/router'
 })
 export class Tab1Page implements OnInit{
   
-  //diaries: Diary[] = [];
-  router: any;
-  authService: any;
+  router: any; 
 
   constructor(
     private modalCtrl: ModalController,
@@ -28,8 +26,6 @@ export class Tab1Page implements OnInit{
     })
   }
   
-
-  //navigateTo(setting?:string){}
   navigateTo(page: string) {
   // 根据传入的页面参数进行导航
   switch(page) {
@@ -47,128 +43,16 @@ export class Tab1Page implements OnInit{
       break;
   }
   
-  // 关闭菜单
-  //const menu = document.querySelector('ion-menu');
-  //menu.close();
 }
   diaryList: CloudObject[]=[];
   async loadDiaries() {
-    let query=new CloudQuery("Diary")
-    //query.equalTo('user',Parse.User.current()?.id)
-    //const currentUser = await CloudUser.current(); // 获取当前用户
+    let query=new CloudQuery("Diary"); 
     this.diaryList=await query.find();
 
   }
 
   ngOnInit() {
     this.diaryList=[];
-
-    
-  }
-
-   async importDiary(){
-    
-  //   // 获取当前用户
-  //   const diaryDataset=[
-  // {
-  //   "Did": 1,
-  //   "date": "15",
-  //   "weekday": "周三",
-  //   "time": "14:30",
-  //   "content": "今天阳光明媚,去公园散步时看到樱花开了。粉色的花瓣随风飘落,美得像一幅画。坐在长椅上读了一会儿书,感觉心情特别平静。",
-  //   "weather": "晴",
-  //   "mood": "😊"
-  // },
-  // {
-  //   "Did": 2,
-  //   "date": "14",
-  //   "weekday": "周二",
-  //   "time": "21:15",
-  //   "content": "项目终于告一段落,加班到很晚但很有成就感。回家的路上买了杯热奶茶犒劳自己,发现常去的那家奶茶店换了新包装,杯子上画着可爱的小兔子。",
-  //   "weather": "多云",
-  //   "mood": "😌"
-  // },
-  // {
-  //   "Did": 3,
-  //   "date": "12",
-  //   "weekday": "周日",
-  //   "time": "09:45",
-  //   "content": "周末尝试做了新的菜谱 - 番茄牛腩。虽然炖的时间比预期长,但结果非常美味!下午窝在沙发上看了一部老电影,窗外下着小雨,这种慵懒的周末真是太棒了。",
-  //   "weather": "小雨",
-  //   "mood": "🥰"
-  // },
-  // {
-  //   "Did": 4,
-  //   "date": "18",
-  //   "weekday": "周五",
-  //   "time": "18:20",
-  //   "content": "参加了公司的团队建设活动,第一次体验了攀岩项目。虽然爬到一半有些害怕,但在同事的鼓励下成功登顶,突破自我的感觉真好!",
-  //   "weather": "阴",
-  //   "mood": "😄"
-  // },
-  // {
-  //   "Did": 5,
-  //   "date": "20",
-  //   "weekday": "周六",
-  //   "time": "15:10",
-  //   "content": "和朋友去了新开的猫咖,有十几只不同品种的猫咪。最喜欢那只胖乎乎的橘猫,它居然在我腿上睡了一下午,治愈了连日的疲惫。",
-  //   "weather": "晴",
-  //   "mood": "😺"
-  // },
-  // {
-  //   "Did": 6,
-  //   "date": "22",
-  //   "weekday": "周一",
-  //   "time": "08:05",
-  //   "content": "早起晨跑时发现小区里的桂花开了,空气里都是甜甜的香气。顺手拍了张晨光中的花枝,设为手机壁纸后整天都有好心情。",
-  //   "weather": "雾",
-  //   "mood": "🌼"
-  // },
-  // {
-  //   "Did": 7,
-  //   "date": "25",
-  //   "weekday": "周四",
-  //   "time": "19:40",
-  //   "content": "下班路上遇到卖糖炒栗子的小摊,热乎乎的栗子捧在手里,边走边吃仿佛回到学生时代。突然想念大学的林荫道和图书馆了。",
-  //   "weather": "微风",
-  //   "mood": "🍂"
-  // },
-  // {
-  //   "Did": 8,
-  //   "date": "28",
-  //   "weekday": "周日",
-  //   "time": "22:30",
-  //   "content": "整理旧物时发现了高中时期的同学录,翻看那些青涩的留言和夸张的贴纸,忍不住笑出声。那些以为忘记的回忆突然都鲜活起来。",
-  //   "weather": "晴",
-  //   "mood": "📖"
-  // }
-  // ]; 
-  //   const Diary=new CloudObject("Diary");
-  //   const query=new CloudQuery("Diary");
-
-  //   for(const diary of diaryDataset){
-  //     try{
-  //       const query=new CloudQuery("Diary");
-  //       //检查是否已存在相同内容
-  //       query.equalTo("Did",diary.Did);
-  //       const existing=await query.first();
-
-  //       if(existing){
-  //         console.log(`日记${diary.content}"已存在,保存跳过`);
-  //         continue;
-  //       }
-  //       //创建新日记
-  //       const newDiary=new CloudObject("Diary");
-  //       newDiary.set(diary);
-
-  //       //保存到数据库
-  //       await newDiary.save();
-  //       console.log(`日记${diary.content}保存成功`);
-  //     }catch(error){
-  //       console.error(`保存日记${diary.content}时出错`,error);
-  //     }
-  //   }
-  //   console.log("所有日记数据处理完成");
   }
 
   async goToEditPage(edit?:string) {

+ 1 - 1
myapp/src/app/tab2/dynamic-create/dynamic-create.page.ts

@@ -77,7 +77,7 @@ export class DynamicCreatePage implements OnInit {
         isPublic: true,
         likeCount: 0,
         commentCount: 0,
-        shareCount: 0
+        shareCount: 0,
       });
 
       // 4. 保存动态

+ 2 - 2
myapp/src/app/tab2/dynamic-detail/dynamic-detail.page.html

@@ -13,7 +13,7 @@
     <div class="user-info">
       <div class="user-avatar">{{ dynamic.get('author')?.username?.charAt(0) || 'U' }}</div>
       <div class="user-details">
-        <div class="user-name">{{ dynamic.get('author')?.username || '匿名用户' }}</div>
+        <div class="user-name">{{ dynamic.get('author')?.objectId || '匿名用户' }}</div>
         <div class="post-time">{{ dynamic.createdAt | date:'yyyy-MM-dd HH:mm' }}</div>
       </div>
     </div>
@@ -56,7 +56,7 @@
       <div class="comment-item" *ngFor="let comment of comments">
         <div class="comment-user">
           <div class="user-avatar">{{ comment.get('user')?.username?.charAt(0) || 'U' }}</div>
-          <div class="user-name">{{ comment.get('user')?.username || '匿名用户' }}</div>
+          <div class="user-name">{{ comment.get('user')?.objectId || '匿名用户' }}</div>
           <div class="comment-time">{{ comment.createdAt | date:'yyyy-MM-dd HH:mm' }}</div>
         </div>
         <div class="comment-content">{{ comment.get('content') }}</div>

+ 2 - 2
myapp/src/app/tab2/tab2.page.html

@@ -19,7 +19,7 @@
 <ion-content [fullscreen]="true">
   <!-- 功能板块 -->
   <div class="function-grid">
-    <div (click)="importData()" class="function-card card-1">树洞</div>
+    <div class="function-card card-1">树洞</div>
     <div (click)="goThankslist('清单')" class="function-card card-2">感恩清单</div>
     <div class="function-card card-3">漂流瓶</div>
     <div (click)="goToManage()" class="function-card card-4">情绪发泄室</div>
@@ -47,7 +47,7 @@
       <div class="user-info">
         <div class="user-left">
           <div class="user-avatar">{{ dynamic.get('author')?.get('username')?.charAt(0) || 'U' }}</div>
-          <div class="user-name">{{ dynamic.get('author')?.get('username') || '匿名用户' }}</div>
+          <div class="user-name">{{ dynamic.get('author')?.objectId|| '匿名用户' }}</div>
         </div>
         <ion-icon name="ellipsis-horizontal" class="more-icon"></ion-icon>
       </div>

+ 29 - 43
myapp/src/app/tab2/tab2.page.ts

@@ -15,6 +15,7 @@ export class Tab2Page implements OnInit {
   isLoading = true; // 添加加载状态变量
   currentUser: any = null;
   dynamics: any[] = [];
+  //dynamics: CloudObject[]=[];
   userInteractions: Record<string, any> = {}; // 记录用户对每个动态的互动状态
   // 在组件类中添加
   tabs = [
@@ -38,35 +39,13 @@ export class Tab2Page implements OnInit {
     this.activatedRoute.params.subscribe(()=>{
       this.loadData();
     })
-  }
-
-  goToManage(){
-    this.navCtrl.navigateForward(["tabs","tab2","management"])
-  }
-
-  // async chaXun(){
-  //   //获取当前用户
-  //   let user:any =new CloudUser();
-  //   console.log(user)
-  //   //user = user.current();
-  //   let query =new CloudQuery("Dynamic")
-  //   query.equalTo("user",user.id)
-  //   //query.include("dynamic");
-  //   console.log(await query.find())
-  // }
-
+  } 
+ 
   async ngOnInit() {
-     await this.loadData();
+     //await this.loadData();
+     this.dynamics=[];
   }
 
-  goToDynamic(dynamicId:string){
-    this.navCtrl.navigateForward(["tabs","tab2","dynamic-detail",dynamicId])
-    //this.router.navigate(['/dynamic-detail', dynamicId]);
-  }
-
-  addDynamic(){
-    this.navCtrl.navigateForward(["tabs","tab2","dynamic-create"])
-  }
 
   async loadData() {
     
@@ -86,6 +65,14 @@ export class Tab2Page implements OnInit {
     dynamicQuery.include("author");
     this.dynamics = await dynamicQuery.find();
 
+    // 调试输出,检查数据
+    // this.dynamics.forEach(d => {
+    //   console.log('Dynamic author:', d.id,'Author:',d.get('author'));
+    //   if (!d.get('author')) {
+    //     console.warn(`动态 ${d.id} 没有作者信息!`);
+    //   }
+    // });
+
     // 查询当前用户的互动
     const interactionQuery = new CloudQuery("Interaction");
     interactionQuery.equalTo("user", this.currentUser.id);
@@ -110,6 +97,9 @@ export class Tab2Page implements OnInit {
       this.isLoading = false; // 结束加载
     }
   }
+  importData(){
+
+  }
 
   // 点赞/取消点赞
   async toggleLike(dynamic: any) {
@@ -255,26 +245,22 @@ export class Tab2Page implements OnInit {
 
     await alert.present();
   }
-
-
-  importData(){
-    importTestData();
-  }
-
+ 
   goThankslist(thanks?:string){
     this.navCtrl.navigateForward(["tabs","tab2","thanks"],{
       
     })
   }
-  navigateToDetail() { // 定义一个方法用于导航到详情页面
-    if (this.router.url !== '/detail') { // 检查当前 URL 是否不是目标页面
-      this.router.navigateByUrl('/detail').then(() => { // 如果不是,则导航到详情页面
-        console.log('Navigation completed.'); // 导航完成后打印日志
-      }).catch(error => { // 捕获并处理可能发生的错误
-        console.error('Navigation failed:', error); // 打印错误信息
-      });
-    } else { // 如果已经是目标页面
-      console.warn('Already on the detail page, no need to navigate.'); // 打印警告信息
-    }
-  } 
+
+   goToManage(){
+    this.navCtrl.navigateForward(["tabs","tab2","management"])
+  }
+  goToDynamic(dynamicId:string){
+    this.navCtrl.navigateForward(["tabs","tab2","dynamic-detail",dynamicId])
+    //this.router.navigate(['/dynamic-detail', dynamicId]);
+  }
+
+  addDynamic(){
+    this.navCtrl.navigateForward(["tabs","tab2","dynamic-create"])
+  }
 }

+ 29 - 11
myapp/src/app/tab4/login/login.page.ts

@@ -11,10 +11,12 @@ import { ToastController } from '@ionic/angular';
   standalone:false,
 })
 export class LoginPage {
-  username = '';
+
+    username = '';
   password = '';
-  isLogin = true; // 切换登录/注册模式
-  email = ''; // 注册时使用
+  email = '';
+  isLogin = true;
+  isLoading = false; // 添加加载状态
 
   constructor(
     private authService: AuthService,
@@ -23,10 +25,21 @@ export class LoginPage {
   ) {}
 
   async submit() {
-    if (this.isLogin) {
-      await this.handleLogin();
-    } else {
-      await this.handleRegister();
+    if (this.isLoading) return;
+    
+    this.isLoading = true;
+    
+    try {
+      if (this.isLogin) {
+        await this.handleLogin();
+      } else {
+        await this.handleRegister();
+      }
+    } catch (error) {
+      console.error('Auth error:', error);
+      this.showToast('操作失败,请稍后重试');
+    } finally {
+      this.isLoading = false;
     }
   }
 
@@ -37,11 +50,10 @@ export class LoginPage {
     }
 
     const success = await this.authService.login(this.username, this.password);
-    console.log(success);
     
     if (success) {
       this.showToast('登录成功');
-      this.router.navigate(['/tabs/tab4']);
+      this.router.navigate(['/tabs/tab1'], { replaceUrl: true });
     } else {
       this.showToast('登录失败,请检查用户名和密码');
     }
@@ -53,15 +65,21 @@ export class LoginPage {
       return;
     }
 
-    const success = await this.authService.register(this.username, this.password, this.email);
+    const success = await this.authService.register(
+      this.username, 
+      this.password, 
+      this.email || undefined
+    );
+
     if (success) {
       this.showToast('注册成功,已自动登录');
-      this.router.navigate(['/tabs/tab1']);
+      this.router.navigate(['/tabs/tab1'], { replaceUrl: true });
     } else {
       this.showToast('注册失败,用户名可能已被使用');
     }
   }
 
+
   toggleMode() {
     this.isLogin = !this.isLogin;
   }

+ 1 - 1
myapp/src/app/tab4/tab4.page.html

@@ -110,7 +110,7 @@
                 </div>
             </div>
             
-            <div class="function-item" (click)="goToAlbum()">
+            <div class="function-item">
                 <div class="function-left">
                     <div class="function-icon">
                         <ion-icon name="images-outline"></ion-icon>

+ 0 - 4
myapp/src/app/tab4/tab4.page.ts

@@ -17,10 +17,6 @@ export class Tab4Page implements OnInit {
   ngOnInit() {
   }
 
-  goToAlbum() {
-  this.navCtrl.navigateForward(["tabs","tab4","album"]);
-  }
-
   goLogin(user?:string){
     this.navCtrl.navigateForward(["tabs","tab4","login"])
   }