我有一個服務,它返回一個對我的服務器執行http請求並獲取數據的observable。我想要使用這些數據,但我總是得到undefined
。有什麼問題?如何從angular2中的Observable/http/async調用返回響應?
服務:
@Injectable()
export class EventService {
constructor(private http: Http) { }
getEventList(): Observable<any>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get("http://localhost:9999/events/get", options)
.map((res)=> res.json())
.catch((err)=> err)
}
}
組件:
@Component({...})
export class EventComponent {
myEvents: any;
constructor(private es: EventService) { }
ngOnInit(){
this.es.getEventList()
.subscribe((response)=>{
this.myEvents = response;
});
console.log(this.myEvents); //This prints undefined!
}
}
這將是一個很好的一點是要強調一個事實,這是不可能改造的臺異步操作的synchrnous一。 – n00dl3
@ n00dl3感謝您的提示!我試圖在「你不該做什麼:」部分解釋。隨意編輯它。 – echonax