초기화 할 때 서비스에서 데이터를 검색하고 배열 인 해당 속성 중 하나를 채우는 클래스가 있습니다. 이 같은 클래스에는 정렬을 필터링하고 반환하는 함수가 있습니다. 이 클래스의 객체를 인스턴스화하고이 함수를 호출하면 해당 생성자와 ngOnInit() 함수가 완료되기 전에 호출 된 것을 알게되었습니다 (아마도 Observables에서 서비스가 반환하는 비동기 컨텐츠를 사용하기 때문에). 내 클래스의 함수가 외부에서 호출되기 전에 생성자와 init이 완전히 실행되도록 어떻게 보장 할 수 있습니까? ,클래스에서 함수를 호출하기 전에 constructor/ngOnInit을 확인하는 방법은 무엇입니까?
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;
});
}
그런 짓을하려고했으나 그것은 나를 그렇게 못하게 리턴 변수가 존재한다는 보장이 없기 때문에 가정합니다.
이것은 외부에서 콘텐츠를 호출하는 방법에 따라 달라집니다. 상위 구성 요소, 지시문, 서비스 등에서 호출되고 있습니까? 지도 기능 후에 목록을 정렬 할 수없는 이유가 무엇입니까? – joh04667
[생성자 함수가 Promise를 반환하도록하는 것은 나쁜 습관입니까?] (http://stackoverflow.com/q/24398699/1048572). 인스턴스를 생성하기 전에 인스턴스의 초기화 (생성자 직접 또는 각도 후크를 통해)에서 비동기적인 작업을 수행하지 마십시오. – Bergi
클래스에서 인스턴스를 만들기 전에 어떻게해야합니까? 생성자가 클래스에서 실행되는 첫 번째 것이 아닌가? –