|
|
@@ -26,6 +26,8 @@ export class WeightDataService {
|
|
|
constructor(private http: HttpClient) {
|
|
|
this.initializeData();
|
|
|
this.startAutoSync();
|
|
|
+ // 启动时立刻从后端拉一次真实数据
|
|
|
+ setTimeout(() => this.syncFromBackend(), 100);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -306,31 +308,32 @@ export class WeightDataService {
|
|
|
* 从后端同步数据
|
|
|
*/
|
|
|
private syncFromBackend(): void {
|
|
|
- // 获取记录
|
|
|
- this.http.get<WeightRecord[]>(`${this.API_BASE}/records`)
|
|
|
- .pipe(catchError(() => []))
|
|
|
- .subscribe(backendRecords => {
|
|
|
+ // 获取记录(后端返回 { success, data: { records, total, page, limit } })
|
|
|
+ this.http.get<{ success: boolean; data: { records: WeightRecord[]; total: number } }>(
|
|
|
+ `${this.API_BASE}/records?limit=100&page=1`
|
|
|
+ )
|
|
|
+ .pipe(catchError(() => of({ success: false, data: { records: [], total: 0 } })))
|
|
|
+ .subscribe(resp => {
|
|
|
+ const backendRecords = resp?.data?.records ?? [];
|
|
|
+ if (backendRecords.length === 0) return;
|
|
|
+
|
|
|
+ // 后端数据优先:直接覆盖本地记录
|
|
|
const localData = this.getLocalData();
|
|
|
-
|
|
|
- // 合并本地和后端数据(后端数据优先)
|
|
|
- const mergedRecords = this.mergeRecords(localData.records, backendRecords as WeightRecord[]);
|
|
|
-
|
|
|
- localData.records = mergedRecords;
|
|
|
+ localData.records = backendRecords;
|
|
|
localData.lastSyncTime = Date.now();
|
|
|
-
|
|
|
this.saveLocalData(localData);
|
|
|
- this.recordsSubject.next(mergedRecords);
|
|
|
+ this.recordsSubject.next(backendRecords);
|
|
|
});
|
|
|
-
|
|
|
+
|
|
|
// 获取目标
|
|
|
- this.http.get<WeightGoal>(`${this.API_BASE}/goal`)
|
|
|
- .pipe(catchError(() => of(null as unknown as WeightGoal)))
|
|
|
- .subscribe(backendGoal => {
|
|
|
- if (backendGoal) {
|
|
|
+ this.http.get<{ success: boolean; data: WeightGoal | null }>(`${this.API_BASE}/goal`)
|
|
|
+ .pipe(catchError(() => of({ success: false, data: null })))
|
|
|
+ .subscribe(resp => {
|
|
|
+ if (resp?.data) {
|
|
|
const localData = this.getLocalData();
|
|
|
- localData.goal = backendGoal as WeightGoal;
|
|
|
+ localData.goal = resp.data;
|
|
|
this.saveLocalData(localData);
|
|
|
- this.goalSubject.next(backendGoal as WeightGoal);
|
|
|
+ this.goalSubject.next(resp.data);
|
|
|
}
|
|
|
});
|
|
|
}
|