import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch'
@Injectable()
export class EquipmentService{
data: any;
constructor(private http:Http){
}
getDefaultEquipment(){
this.http.get('./app/SaveData/equipmentTest.json')
.map((res:Response) => res.json())
.subscribe(data => { this.data = data},
err => console.error(err),
() => console.log(this.data));
}
}
從文件中讀取數據,重要的是getDefaultEquipment()
。Angular 2 observable如何提取響應?
如果您看到最後一個console.log(this.data)數據是正確的,那正是我所需要的。但如果我return this.http.get(...() => {return this.data})
我得到未定義。我如何獲得並返回此數據?
很顯然,如果我編寫另一個如下所示的返回值,那麼observable尚未完成,因此它將返回空數據:any。
//clearly won't work because the get hasn't returned yet
getDefaultEquipment(){
this.http.get(...data => {this.data = data}...);
return this.data;
}
只需返回您的可觀察值。您不需要將異步呼叫轉換爲同步呼叫。 – Cleiton
您無法返回數據。不要訂閱。只要返回可觀察的。調用者將是訂閱者,並將獲得傳遞給subscribe()的回調函數中的數據。 –
太棒了。那就是訣竅。在我的設備組件'this.equipmentService.getDefaultEquipment()中添加了訂閱方法subscribe( stuff => {console.log(stuff)}, );'謝謝。 –