Reputation: 2219
I am trying to load a local JSON in a component
My code as below:
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()));
}
}
Issue:
If I refresh the browser page, the gameStore
is not loaded data, I receive the log as below:
info : {}
Any Suggestion is appreciated
Upvotes: 0
Views: 652
Reputation: 421
Everything you are doing is executing asynchronously. But you are calling getValue() synchronously. So the data may not be present at the time you are calling, but may come after that time. So you should call getValue() in a subscribe method. As you are injecting store.ts in your component, you can easily access the game observable.
this.gameStore.game.subscribe(data => console.log('info: ' + JSON.stringify(data));
Upvotes: 2