0
votes

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.

1

1 Answers

0
votes

You should return Observable<Student[]> from thegetRoster` method like this

getRoster(): Observable<Student[]>{
       return this.http.get('/JSON/students.json')
            .map(data => data.json().students);
    }

and then subscribe to the result in the app component

export class AppComponent {
    public students : Student[];
    constructor(private _rosterService : RosterService) {
       _rosterService.getRoster().subscribe(students => this.students = students);
    }
 }

In addition, it is better to call the service in ngOnInit by implementing OnInit interface.