2016-07-25 13 views
2

TypeScriptでAngular 2の約束をどのように使うのかちょっと混乱します。たとえば、JSONを取得するサービスを作成しましたが、その結果を配列に設定したいとします。角度1で例えばのでAngular 2とTypeScriptを使って約束を変える方法

、私は次の操作を行います:角2で

workService.getAllWork().then(function(result){ 
    vm.projects = result.projects; 
}); 

私は、次のサービスがあります。

import {Injectable} from '@angular/core'; 
import {Http, Response} from '@angular/http'; 
import {Observable} from 'rxjs/Observable'; 

@Injectable() 
export class WorkService { 
constructor(private _http: Http) { } 
    getAllProjects() { 
    return this._http.get('/fixture/work.json') 
     .map((response: Response) => response.json().projects) 
     .do(projects => console.log('projects: ', projects)) 
     .toPromise() 
     .catch(this.handleError); 
    } 

    private handleError(error: Response) { 
    console.error(error); 
    return Observable.throw(error.json().error || 'Server error'); 
    } 
} 

そして、私のコンポーネントでのI持っている:

ご協力いただければ幸いです。

答えて

2

Promiseの場合は、.then(...)を使用してコールをチェーンします。

ngOnInit() { 
    this.workService.getAllProjects().then(value => this.projects = value); 
    } 

あなたは、ラムダ式、超便利おかげで

ngOnInit() { 
    this.workService.getAllProjects().then(value => { 
     this.workService = value; 
     // more code here 
    }); 
    } 
+1

新規作成]を使用し、あなたが約束が解決した後にコードを実行したい場合は

ngOnInit() { this.workService.getAllProjects().then(value => this.workService = value); // <=== code here is executed before 'this.workService.value' is executed } 

ことに注意する必要があります。 –

+0

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions –

関連する問題