我的Angular2服务有问题。我的函数调用休息服务器,接下来我想打印输出但console.log
显示undefined
。
主要课程
export class EventListComponent implements OnInit {
events: Event[];
constructor(
private eventService: EventService
) {}
loadPosts() {
console.log('loading');
this.eventService.getEvents()
.subscribe(
events => this.events = events,
err => {
console.log(err);
});
console.log(this.events); // undefined
}
ngOnInit() {
// Load comments
this.loadPosts();
}
}
和EventService
@Injectable()
export class EventService {
private eventsUrl = 'http://localhost:5000/search';
constructor(private http: Http) {}
getEvents(): Observable<Event[]> {
return this.http.get(this.eventsUrl)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
}
什么是错的?
答案 0 :(得分:0)
您在设置之前正在记录this.events
。做:
loadPosts() {
this.eventService.getEvents()
.catch(err => console.log(err))
.subscribe(
events => {
this.events = events;
console.log(this.events);
});
}