2016-07-25 24 views
2

Im如何在使用TypeScript的Angular 2中使用承諾有點困惑。例如,我創建了一個獲取一些JSON的服務,我想將結果設置爲一個數組。如何在使用Angular 2和TypeScript的承諾中設置變量

因此,例如在角1,我將做到以下幾點:

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

在角2,我有以下服務:

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有:

import {Component} from '@angular/core'; 
import {HTTP_PROVIDERS} from '@angular/http'; 
import {Showcase} from '../showcase/showcase.component'; 
import {WorkService} from '../services/work.service'; 

@Component({ 
    selector: 'App', 
    template: require('./landing.html'), 
    directives: [Showcase], 
    providers: [HTTP_PROVIDERS, WorkService] 
}) 

export class Landing { 
    public projects: Array<any>; 

    constructor(private _workService: WorkService) {} 

    ngOnInit() { 
    // How would I set the projects array to the WorkService results 
    } 
} 

任何幫助將不勝感激。

回答

2

對於Promise,您使用.then(...)來鏈接呼叫。

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

你應該知道,

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

如果你想解決的承諾後執行代碼,使用

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

新的lambda表達式,超級有幫助的感謝。 –

+0

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

相關問題