Search code examples
angulartypescriptangular2-services

ng2 Get Object from HttpGet Service


I am trying to get JSON data from my WebAPI and it's not working. I always get undefined whenever I try to use that return object in my component.

I would like to display the student and course data on the home landing page of my website. At the moment, my controller / api is returning the hardcoded data.

student.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';

@Injectable()
export class StudentService {
    private http: Http;            

    constructor(http: Http) {
        this.http = http;
    }

    getStudentCourse(): Observable<IStudentCourse> {
        var model: IStudentCourse;

        this.http.get('/api/student/getstudentcourse').subscribe(result => {
            model = result.json() as IStudentCourse;

            console.log(model);            

        }, error => console.log('Could not load data.'));

        console.log("model: outside of httpget: " + model);

        return Observable.of(model);        
    }
}

export interface IStudentCourse {
    refNo: string;
    student: number;
    offeringName: number;
    offeringID: string;
}

I can confirm that my service is returning JSON data and I can see it in Network Traffic and can see it my console.

enter image description here

home.component.ts

import { Component, OnInit } from '@angular/core';
import { StudentService, IStudentCourse } from './student.service';

@Component({
    selector: 'home',
    templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {    

    studentCourse: IStudentCourse;
    Message: string;

    constructor(
        private _studentService: StudentService) {        
    }

    ngOnInit(): void {
        this.getStudentCourse();
        console.log("fromngOnInit");
        console.log("Init: " + this.studentCourse.offeringName);
    }

    getStudentCourse() {        
        this._studentService.getStudentCourse().subscribe(
            item => this.studentCourse = Object.assign({}, item),
            error => this.Message = <any>error);
    }
}

You can see in my screenshot that, studentCourse is always null in ngOnInit and I couldn't manage to bind it.

Could you please help me with this error? Thanks.

Updated: plnkr Link

I prefer to put this HttpGet service in the separate service file because I need to use it in other components too.


Solution

  • see plunker : plunker

    in your template use ?:

    <h2>Hello {{studentCourse?.student}}</h2>
    

    don't subscribe in the service , you can do this:

     getStudentCourse(): Observable<IStudentCourse> {
            let model: IStudentCourse;
    
            return this.http.get('/api/student/getstudentcourse').map(result => {
                model = result.json() as IStudentCourse;
                return model;
            }).catch( error => console.log('Could not load data.'));
    
        }