2016-07-20 154 views
0

我正在使用Angular和RxJS編寫項目。我實現了注射類從JSON這樣的檢索數據:在Angular中的異步函數返回

import {Injectable, Inject} from '@angular/core'; 
import {Http} from '@angular/http'; 
import 'rxjs/add/operator/map'; 

import {Student} from './student.data'; 

@Injectable() 
export class RosterService { 
    private students : Student[]; 
    constructor(@Inject(Http) private http:Http){} 

    private getStudents(){ 
     this.http.get('/JSON/students.json') 
      .map(data => data.json().students) 
      .subscribe(data => this.students = data); 
    } 

    public getRoster() { 
     this.getStudents(); 
     return this.students; 
    } 
} 

後我注入RosterService到AppComponent的構造(包括成@Component作爲供應商):

export class AppComponent { 
    public students : Student[]; 
    constructor(private _rosterService : RosterService) { 
     this.students = _rosterService.getRoster(); 
    } 
} 

但是當我打電話getRoaster()方法,它不會等到getStudents(異步獲取調用)被執行。在結果我得到未定義的值。

我該如何處理?感謝您的迴應。

+0

擴展我的問題裏面。這是不一樣的。 –

+0

完全一樣。你剛剛添加了幾個圖層。你希望getRoster同步運行getStudents(IOW,在返回this.students之前完成)。重複討論如何構建您的代碼來實現這一目標。 –

回答

1

我會使用回調函數,例如,如果它是一個承諾,那麼我會用下面的東西。

var data; 
asyncCall().then((result:any) => { 
data = reuslt; 
return data; 
}); 

不知道這是你尋找的。

更新時間:

 @Injectable() 
    export class RosterService { 
     private students : Student[]; 
     constructor(@Inject(Http) private http:Http){} 

     private getStudents(){ 
      return this.http.get('/JSON/students.json') 
       .map(data => data.json().students) 
       .subscribe(data => this.students = data); 
     } 

     public getRoster() { 
      return this.getStudents().then (() =>{ 
    return this.students; 
      });   
     } 
     } 

而且你AppComponent

export class AppComponent { 
    public students : Student[]; 
    constructor(private _rosterService : RosterService) { 
     this._rosterService.getRoster().then ((data:<T>)=>{ 
     this.students =data; 
    }); 
    } 
} 
+0

對不起,誤導我,我錯誤地表達了我的問題。調整它。 –

+0

在$ http上使用then然後返回數據。 – Aj1

+0

我不知道,Javascript中是否正確,但在Typescript中,您不允許在異步調用中返回值 –

0

在我看來,你基本上錯過了Javascript中的一個關鍵設計模式,這是一個回調。

而不是從函數返回值,而是傳遞一些代碼以在函數良好且準備就緒時執行。

function doSomething(success) { 
    var data = 1; 
    // blah blah blah, something happens. 
    success(data); 
} 

function myFunction(data) { 
    console.log(data); 
} 

doSomething(myFunction); 

這樣,您就可以保持調用的異步性質,而不會阻塞Javascript可用的單個線程。

+0

對不起,誤導我,我錯誤地表達了我的問題。現在調整它。 –

0

我假設你的異步函數返回promise。


首先,邏輯是一種奇怪的有.. data的作用範圍是功能,func不能訪問data

這裏是你可能想做什麼:

function() { 
    return func().then(data => data) 
} 

除了使該與此相同:

function() { 
    return func() 
} 

..和在這種情況下,你可能也只是更換功能與func

func 

(或者,如果func一些其他的對象,() => func()的屬性。)

編輯:這項新功能是一個異步功能,因此它當然會返回一個承諾。您稍後需要使用.then才能從中獲取數據。

+0

抱歉有誤導性,我錯誤地表達了我的問題。現在調整它。感謝您的評論和範圍 - 我放棄了它。 –