46 lines
1.4 KiB
Plaintext
46 lines
1.4 KiB
Plaintext
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;
|
||
}
|
||
}
|
||
}
|