2017-06-21 58 views
0

我正在通過Get請求查找API中的數據,我需要我的OnInit中的數據用於撰寫其他數據。問題在於該方法正在被調用,但它是一個異步方法(無需等待),它在任何地方通過,但是當獲得返回時,主方法的執行已經完成,沒有結果。我嘗試了異步方法的實現,但沒有解決。獲取過去的請求而無需等待回覆(Angular 2 +)

服務:

getObjects(): MyClass[] { 
let objects = new Array<MyClass>(); 

this.obterTodos<MyClass>(this.uriApi) 
    .map(res => res.map(x => new MyClass(x.Description, x.Id))) 
    .subscribe(entities => { 
     objects = entities; 
    }); 

    return objects ; 
} 

GET請求

public getObjects<TEntity>(url: string): Observable<TEntity[]> { 
    return this.httpService 
     .get(this.serviceUrl + url, this.options) 
     .map(res => res.json()) 
     .catch(this.handleError); 
} 

組件:

ngOnInit() { 
    this.myObjects= this.setorService.obterSetores(); 
    console.log('this.myObjects is empty here'); 
} 

回答

1

所以你要訂閱組件中的可觀察值。通常這樣做是爲了讓組件可以確定何時應該運行http請求&,以便組件可以等待http請求完成(並遵循一些邏輯)。

// subscribe to observable somewhere in your component (like ngOnInit) 
this.setorService.obterSetores().subscribe(
    res => { 
     this.myObjects = res; 
    }, 
    err => {} 
) 

現在組件知道當HTTP請求完成

+0

這樣做的問題是,我將不得不復制我想從一個API的對象是列表中的每個組件的代碼是...那對嗎? –

+1

這是正確的。您可以做的一件事就是在最初調用api時存儲api的結果。那麼每個需要數據的後續組件都可以使用存儲的數據 – LLai