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');
}
這樣做的問題是,我將不得不復制我想從一個API的對象是列表中的每個組件的代碼是...那對嗎? –
這是正確的。您可以做的一件事就是在最初調用api時存儲api的結果。那麼每個需要數據的後續組件都可以使用存儲的數據 – LLai