I'm currently facing an issue with retrieving JSON data from my WebAPI. Every time I attempt to use the returned object in my component, it displays as undefined
.
The goal is to showcase student and course data on the homepage of my website. Currently, my controller / API is returning 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 verify that my service successfully returns JSON data which I can see in Network Traffic and my console.
https://i.sstatic.net/SaeEN.png
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);
}
}
In the screenshot provided, it's evident that studentCourse
is consistently null during ngOnInit
, making it difficult to bind.
I would greatly appreciate any assistance in resolving this issue. Thank you.
Updated: plnkr Link
To enhance reusability across multiple components, I've chosen to keep this HttpGet service in a separate file.