Angular2 rxjs调用rest api并得到未定义的输出

时间:2017-05-28 14:56:31

标签: rest angular

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

}

什么是错的?

1 个答案:

答案 0 :(得分:0)

您在设置之前正在记录this.events。做:

  loadPosts() {

    this.eventService.getEvents()
      .catch(err => console.log(err))
      .subscribe(
        events => {
          this.events = events; 
          console.log(this.events);
      });
  }