Files
harmony-client/entry/src/main/ets/viewmodel/HomeViewModel.ets
2026-09-11 20:48:04 +08:00

46 lines
1.4 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { HomeData } from '../model/HomeModels';
import { HomeRepository } from '../data/repository/HomeRepository';
import { SessionRepository } from '../data/repository/SessionRepository';
import { ServiceLocator } from '../di/ServiceLocator';
/**
* 首页视图模型:@ObservedV2 三态(loading / error / data)。
* 根据登录态分流到游客首页 / 原生首页。
*/
@ObservedV2
export class HomeViewModel {
@Trace data: HomeData = new HomeData();
@Trace isGuest: boolean = true;
@Trace loading: boolean = false;
@Trace error: string = '';
private readonly repository: HomeRepository;
private readonly session: SessionRepository;
constructor(repository: HomeRepository, session: SessionRepository) {
this.repository = repository;
this.session = session;
}
static create(): HomeViewModel {
return new HomeViewModel(
ServiceLocator.get('homeRepository') as HomeRepository,
ServiceLocator.get('sessionRepository') as SessionRepository
);
}
async load(): Promise<void> {
this.loading = true;
this.error = '';
try {
const loggedIn = this.session.isLoggedIn();
this.isGuest = !loggedIn;
this.data = loggedIn ? await this.repository.observeHome() : await this.repository.observeGuestHome();
} catch (err) {
this.error = JSON.stringify(err);
} finally {
this.loading = false;
}
}
}