angular - ng2 从 HttpGet 服务获取对象

标签 angular typescript angular2-services

我正在尝试从 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/

相关文章:

angular - 使用 Angular 从 URL 中提取 id(2+ 直到最新)

c# - 创建用于基于策略的授权期间拒绝访问的自定义页面

css - Angular Transform Scale - 删除空白

angular - 如何使异步数据以 Angular 动态形式模式工作

javascript - 通过字符串注入(inject)和解析 Angular2 提供程序

angular - 如何使用exceljs以 Angular 导入EXCEL文件

angular - 我怎样才能让 typescript 相信可以在 Subject 上调用 Observable 运算符?

angular - mat-date-range-input 不是已知元素 [Angular Material ]

javascript - Angular2 Click 方法总是返回 false 值

typescript - 如何避免在 Angular 2 中导入相对路径很长的内容?