0

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 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.