2017-09-19 10 views
2

APIにhttp.getを呼び出す関数があり、戻り値の型が約束されています。返されたデータを処理/ソートしたいと思います。それを反復処理するには、プロミスをオブジェクトの配列に変換する必要がありますか?Typescriptの約束を使って作業する

getCandidates(): Promise<Candidate[]> { 
    return this.http.get(url) 
     .retry(2) 
     .map(x => { 
     var result: Candidate[] = x.json(); 
     return result; 
     }) 
     .toPromise(); 
    } 

と私は示すことによって関数を呼び出す:ここ は、関数である

this.candidates = this.getCandidates(); 

だから私は今タイプPromise<Candidate[]>のこの候補オブジェクトを持っているが、私はそれがタイプCandidate[]であることがしたいのですが私はそれを使って作業することができます。 candidates.lengthなどこれについてどうすればいいですか?多分私はこれを間違った方法で考えているのかもしれません。

編集:コードを使用しようとしています。

ionViewDidLoad() { 
    //Retrieves candidates and stores into an array 
    this.getCandidates().then(candidates => this.candidates = candidates); 
    console.log(this.candidates); 
    } 

コンソールに空の配列が記録されます。私はまた、それをソート関数に渡そうとしましたが、データはありませんでした。これはhtmlでもhtmlの候補者がデータを取得しているので(これが以前は正しく動作していると思ったからです)、これは奇妙です。

+0

ます'map'の中でそれを行うことができます –

+0

' this.getCandidates()。then(function(candidate){{}}); ' – marekful

+0

@AlekseyLのマップでは配列に結果をプッシュしますか? – Zachscs

答えて

1

あなたは、でngOnInitをあなたの候補を取得this.candidatesにそれを保存して、あなたはそれでやりたいことができます(ソート、...)

candidates: Candidate[] = []; 
 
    
 
    ngOnInit() { 
 
    this.getCandidates().then(candidates => this.candidates = candidates); 
 
    } 
 
    
 
    getCandidates(): Promise<Candidate[]> { 
 
    return this.http.get(url) 
 
     .retry(2) 
 
     .map(x => x.json as Candidate[]) 
 
     .toPromise(); 
 
    }

+0

になりました。今度はnogOnInitを使用しないので、このシナリオでは十分ですionViewDidLoadですか? – Zachscs

+0

百万円ありがとう! – Zachscs

+0

あなたは歓迎です – Faly