Angular: 刷新浏览器页面后无法重新加载数据

Angular: Data cannot reload after refresh browser page

我正在尝试在组件中加载本地 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 : {}

欢迎任何建议

你所做的一切都是异步执行的。但是您正在同步调用 getValue() 。因此数据可能在您呼叫时不存在,但可能在那之后出现。所以你应该在订阅方法中调用 getValue() 。当您在组件中注入 store.ts 时,您可以轻松访问游戏可观察对象。

this.gameStore.game.subscribe(data => console.log('info: ' + JSON.stringify(data));