我有一个服务,它返回一个对我的服务器执行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