我正在尝试从 WebAPI 获取 JSON 数据,但它不起作用。每当我尝试在组件中使用该返回对象时,我总是会得到undefined
。
我想在我网站的主页上显示学生和类(class)数据。目前,我的 Controller /API 正在返回硬编码数据。
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;
}
我可以确认我的服务正在返回 JSON 数据,并且我可以在网络流量中看到它,并且可以在我的控制台中看到它。
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);
}
}
您可以在我的屏幕截图中看到,studentCourse
在 ngOnInit
中始终为 null,并且我无法绑定(bind)它。
您能帮我解决这个错误吗?谢谢。
更新: plnkr Link
我更喜欢将此 HttpGet 服务放在单独的服务文件中,因为我也需要在其他组件中使用它。
最佳答案
您正在返回模型的 n Observable,该模型当时为空。它是异步的。
试试这个:
getStudentCourse(): Observable<IStudentCourse>: {
return this.http.get('/api/student/getstudentcourse')
.map(result => result.json() as IStudentCourse)
.catch(() => throw 'Could not load data.');
}
关于angular - ng2 从 HttpGet 服务获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42905990/