首页 > 解决方案 > Angular、Promise 或 Observable 中的异步调用

问题描述

我知道这是一个非常常见的话题,但我被困住了,我无法理解所有的解决方案。

我有一个 Angular 6 应用程序,它调用 Java Spring 中的 API 来查询数据库。

我的问题是,例如在一页上,我必须在组件中多次查询数据库。

nbOnInit() 执行 getGames()、getTasks() 和 getGlobalProgress()。

第一个问题是 getGames() 迟到了,在 chrome 控制台中我有几个问题,例如“无法读取未定义的属性 'title'”(这是 Game 类型的属性),当 Games[] 是终于解决了,它应该显示。我怎样才能抑制这些错误?

第二个问题是在 getGlobalProgress() 中我需要 this.progress,这在之前的 getTasks() 中受到影响。但是 getTasks() 又迟到了,并且 this.globalProgress 永远不会设置......

我想我需要某种异步调用,比如 Promise 或 observable,我认为“.subscribe”就足够了,但我错了。我在网上找到了很多代码示例,但我不知道该使用哪一个,或者如何使用它。我会很感激一些帮助,非常感谢。

这是相关组件的 ts 文件:

export class SingleGameComponent implements OnInit {

private game: Game[];
private tasks: Task[];
private progress: Progress[];
private globalProgress: number;
private id: any; // Game id

constructor(private gameService: GameService, 
            private route: ActivatedRoute,
            private taskService: TaskService,
            private progressService: ProgressService) { }

ngOnInit() {
  this.id = this.route.snapshot.params['id'];
  this.getGames();
  this.getTasks();
  this.getGlobalProgress();
}

getGames(): void {
  this.gameService.getGameById(+this.id)
    .subscribe(game => this.game = game);
}

getTasks(): void{
  this.taskService.getTasksByGameId(+this.id)
    .subscribe(task => this.tasks = task);

  this.progressService.getProgressByUserAndGame(JSON.parse(localStorage.getItem('currentUser')).id, +this.id)
  .subscribe(progress => this.progress = progress);
}

getGlobalProgress(): void{
  this.progressService.calculateGlobalProgress(this.progress)
  .subscribe(globalProgress => this.globalProgress = globalProgress);
}

}

这是来自服务的一种方法(它们都是相同的):

    getGameById(id: number){
  return this.httpClient.get<Game[]>(this.BASE_URL+'game/id/'+id);
}

标签: angulartypescriptasynchronouspromiseobservable

解决方案


推荐阅读