-1

I have problem with my Angular2 service. My function call to rest server, next I would like to print output but console.log shows undefined.

Main class

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();
  }
}

And 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'));
  }

}

Whats is wrong?

lukassz
  • 3,135
  • 7
  • 32
  • 72
  • 2
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – eko May 28 '17 at 15:07

1 Answers1

0

You're logging this.events before it is set. Do:

  loadPosts() {

    this.eventService.getEvents()
      .catch(err => console.log(err))
      .subscribe(
        events => {
          this.events = events; 
          console.log(this.events);
      });
  }
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175