【发布时间】:2017-08-20 17:01:48
【问题描述】:
我有一个服务,它返回一个 observable,它向我的服务器发出 http 请求并获取数据。我想使用这些数据,但我总是得到undefined。有什么问题?
服务:
@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!
}
}
我查看了How do I return the response from an asynchronous call? 的帖子,但找不到解决方案
【问题讨论】:
-
这将是一个很好的重点,强调不可能将异步操作转换为同步操作。
-
@n00dl3 感谢您的提示!我试图在“你不应该做的事情:”部分进行解释。随意编辑它。
-
@HereticMonkey 该帖子已被记入答案
-
@HereticMonkey 是的,因为它是特定于框架的,它是可观察的。当我用那个答案复制 angular/rxjs,异步问题时,人们感到困惑并说
thening observable 不起作用;这对angular回答者来说是显而易见的,但对你来说显然不是。我也认为在答案中给予信任就足够了,但我也会改变问题。
标签: javascript angular asynchronous typescript observable