I'm writing project using Angular and RxJS. I implemented injectable class that retrieves data from JSON like this:
import {Injectable, Inject} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
import {Student} from './student.data';
@Injectable()
export class RosterService {
private students : Student[];
constructor(@Inject(Http) private http:Http){}
private getStudents(){
this.http.get('/JSON/students.json')
.map(data => data.json().students)
.subscribe(data => this.students = data);
}
public getRoster() {
this.getStudents();
return this.students;
}
}
After I inject RosterService into constructor of AppComponent (including into @Component as provider):
export class AppComponent {
public students : Student[];
constructor(private _rosterService : RosterService) {
this.students = _rosterService.getRoster();
}
}
But when I call getRoaster() method, it doesn't wait until getStudents (async get call) is executed. In the result I get undefined value.
How can I deal with it? Thanks for responce.