angular - 如何加载数据并返回承诺?
问题描述
我有一个模型类:
export class Model {
constructor(public model: any, public repository: RepositoryService) {
}
public hasChildren(id: number) {
return this.model.childs && this.model.findIndex((opt) => opt.id == id) == -1;
}
public getChildren(id: number): Promise<any> {
return new Promise((resolve, reject) => {
if (this.hasChildren(id)) {
resolve(this.model.childs);
} else {
this.repository.loadChildren().subscribe((response) => {
resolve(response);
})
}
});
}
}
// 创建实例
this.model = new Model(dataModel, this.repositoryService);
如果模型中没有,我尝试获取数据或加载:
this.model.getChildren(value).then((data) => {
console.log(data);
});
我的问题在于public getChildren(id: number): Promise<any> {}
方法。如何在这里正确使用promise?
解决方案
我认为您不必创建一个 Promise 对象(因为您在任何情况下都不会拒绝它),请尝试以这种方式使用 async/await 语法:
async public getChildren(id: number): Promise<any> {
if (this.hasChildren(id))
return (this.model.childs)
return (await this.repository.loadChildren().toPromise())
}
推荐阅读
- puppet - 我可以省略 site.pp 在所有节点上执行一个类吗
- javascript - 遍历范围[]
- python - Flask - 与两个表的关系
- python - Flask SQLAlchemy 自定义方法
- html - 溢出和弹性:通过 CSS 改变边框的大小
- angular - 使用 AngularFire v6 使用 Firebase 发送电子邮件验证
- linux - case语句中的多个条件,bash
- python - 在 Python 中将字符串“ddMONyyyy”转换为日期
- c# - C# MVVM Prism 问题
- java - 在 Spring Boot 中使用 ModelMapper 映射列表集合时的问题