ng2 从 HttpGet 服务中获取对象 [英] ng2 Get Object from HttpGet Service
问题描述
我正在尝试从我的 WebAPI 获取 JSON 数据,但它不起作用.每当我尝试在我的组件中使用该返回对象时,我总是得到 undefined
.
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.
我想在我网站的主页登录页面上显示学生和课程数据.目前,我的控制器/api 正在返回硬编码数据.
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;
}
我可以确认我的服务正在返回 JSON 数据,我可以在网络流量中看到它,并且可以在我的控制台中看到它.
I can confirm that my service is returning JSON data and I can see it in Network Traffic and can see it my console.
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,我无法绑定它.
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.
更新: plnkr 链接
我更喜欢将这个 HttpGet 服务放在单独的服务文件中,因为我也需要在其他组件中使用它.
I prefer to put this HttpGet service in the separate service file because I need to use it in other components too.
推荐答案
参见 plunker
: plunker
在你的模板中使用 ?
:
<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.'));
}
这篇关于ng2 从 HttpGet 服务中获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!