我正在尝试在组件中加载本地JSON
我的代码如下:
service.ts
export class GameService {
constructor(private httpClient: HttpClient) {}
loadGameInfo(): Observable<Game> {
return this.httpClient.get<Game>('/assets/mock/game_info.json');
}
}
store.ts
export class GameStore {
private gameSubject = new BehaviorSubject(new Game());
public game: Observable<Game> = this.gameSubject.asObservable();
private isInitialized = false;
constructor(private gameService: GameService) {}
public loadIfEmpty(): void {
if (!this.isInitialized) {
this.isInitialized = true;
this.load();
}
}
public load(): void {
this.gameService
.loadGameInfo()
.pipe(
tap((game: Game) => {
this.gameSubject.next(game);
})
)
.subscribe();
}
public getGame(): Game {
return this.gameSubject.getValue();
}
}
component.ts
export class GameInfoComponent implements OnInit {
constructor(
private gameStore: GameStore) {}
ngOnInit() {
this.gameStore.loadIfEmpty();
console.log('info: ' + JSON.stringify(this.gameStore.getGame()));
}
}
问题:
如果刷新浏览器页面,则gameStore
未加载数据,我将收到以下日志:
info:{}
任何建议都值得赞赏
答案 0 :(得分:2)
您正在做的所有事情都是异步执行的。但是您正在同步调用getValue()。因此,数据可能在您呼叫时不存在,但可能在那之后出现。因此,您应该在subscribe方法中调用getValue()。在组件中注入store.ts时,您可以轻松访问可观察的游戏。
this.gameStore.game.subscribe(data => console.log('info: ' + JSON.stringify(data));