gpt4 book ai didi

angular - ng2 从 HttpGet 服务获取对象

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:48 24 4
gpt4 key购买 nike

我正在尝试从我的 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 数据,我可以在网络流量中看到它,并且可以在我的控制台上看到它。

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);
}
}

您可以在我的屏幕截图中看到,studentCoursengOnInit 中始终为 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.');

}

参见 this plunker

关于angular - ng2 从 HttpGet 服务获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42905990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com