【发布时间】:2017-06-23 21:26:31
【问题描述】:
我有一个类,它在初始化时从服务中检索数据并填充其属性之一,即数组。这个类有一个排序、过滤和返回这个数组的函数。 当我实例化这个类的一个对象并调用这个函数时,我意识到它是在它的构造函数和 ngOnInit() 函数完成之前被调用的(可能是因为我使用了服务返回的 Observables 中的异步内容)。在外部调用我的类的任何函数之前,如何保证构造函数和 init 已经完全执行?
export class BaseChoice implements PickAppraiser, OnInit {
weight = 0;
options = new Array<PickQuality>();
constructor(private championService: ChampionService) {}
ngOnInit() {
// Iterates through the list of champions adding them to the current object
this.championService.getChampions()
.subscribe(champions => {
// Iterates through the list of champions adding them to the current object
Object.keys(champions).map(key => this.options.push(new PickQuality(champions[key], 0)))
})
}
choose(n?: number): PickQuality[] {
var sorted = this.options.sort((a, b) => a.score - b.score);
return sorted;
}
}
我也尝试过做类似的事情
choose(n?: number): PickQuality[] {
// Iterates through the list of champions adding them to the current object
this.championService.getChampions()
.subscribe(champions => {
// Iterates through the list of champions adding them to the current object
Object.keys(champions).map(key => this.options.push(new PickQuality(champions[key], 0)))
this.reevaluate(this.options);
var sorted = this.options.sort((a, b) => a.score - b.score);
var chosen;
if(n) chosen = sorted.slice(1, n);
else chosen = sorted.slice(1, 2);
return chosen;
});
}
我在 choose() 方法本身中运行异步请求的地方,但它不会让我这样做,我假设是因为返回变量不能保证存在。
【问题讨论】:
-
这取决于内容是如何被外部调用的。它是否被父组件、指令、服务等调用?有什么原因你不能在 map 函数之后对列表进行排序?
-
看看Is it bad practice to have a constructor function return a Promise?。不要在初始化实例时做任何异步操作(直接通过构造函数或角度钩子),在创建实例之前做。
-
在类中创建实例之前如何做任何事情?构造函数不是在类中运行的第一件事吗?
-
您可以做的最简单(虽然不是最优雅)的事情就是在您制作课程时不初始化选项。然后在您的模板中,您可以执行
options?.doSomething()或*ngIf(options)
标签: angular promise angular-promise angular2-services