angular - 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);
}
解决方案
推荐阅读
- ios - 'UIKit/UIUserActivity.h' 文件未找到,Xcode 9.4
- continuous-integration - 如何将 Concourse resource_types 定义存储在外部文件中并将它们导入管道?
- c++ - 在 NS2 中将 C++ 函数返回值推送到 OTcl
- spring-boot - 无法在 Kubernetes Spring Boot 应用程序中设置会话 cookie 最大年龄
- r - 基于多个变量重新排序列表
- android - Android 关闭屏幕上的图标
- azure - 静态托管 - 单个 blob 存储帐户中的多个网站
- ubuntu-18.04 - 升级到 laravel 6.0 - 由于“默认”方法,工作迁移现在失败,可能是 MariaDB 问题
- macos - 如何在 Mac OS 中将我的 .app 转换为 .dmg,其中包含一些额外的隐藏文件
- java - JDK11 异常;客户端首选项不接受服务器选择的协议版本 TLS10 [TLS13, TLS12, TLS11]