0
我的Angular2服務有問題。我的函數調用休息服務器,接下來我想打印輸出,但console.log
顯示undefined
。Angular2 rxjs調用休息API並獲取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'));
}
}
請告訴我是錯了嗎?
的[?我如何返回從angular2可觀察/ HTTP /異步調用的響應(可能的複製https://stackoverflow.com/questions/43055706/how-do-i-return -the-響應從 - 一個可觀測-HTTP-異步-通話中angular2) – echonax