ng2 从 HttpGet 服务获取对象

ng2 Get Object from HttpGet Service

我正在尝试从我的 WebAPI 获取 JSON 数据,但它无法正常工作。每当我尝试在我的组件中使用那个 return 对象时,我总是得到 undefined

我想在我网站的主页登录页面上显示学生和课程数据。目前,我的控制器/api正在return处理硬编码数据。

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

我可以确认我的服务正在 returning 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);
    }
}

您可以在我的屏幕截图中看到,studentCoursengOnInit 中始终为空,我无法绑定它。

你能帮我解决这个错误吗?谢谢。

更新: plnkr Link

我更喜欢将这个HttpGet服务放在单独的服务文件中,因为我也需要在其他组件中使用它。

参见 plunker : plunker

在您的模板中使用 ?:

<h2>Hello {{studentCourse?.student}}</h2>

不订阅该服务,您可以这样做:

 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.'));

    }

你正在返回你的模型的一个 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

您可以为此任务使用 BehaviorSubject,并在您的 Http 订阅中为主题发出一个新值。

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http } from '@angular/http';
import { BehaviorSubject } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';


@Injectable()
export class StudentService {
    private studentCourse: BehaviorSubject<IStudentCourse> = new BehaviorSubject<IStudentCourse>(null);

    public get studentCourse$() { 
        return this.studentCourse.asObservable();
    }

    constructor(private http: Http) { }

    getStudentCourse() {
       this.http.get('https://58cff77fe1a0d412002e446d.mockapi.io/api/student/getstudentcourse/2').map(response => {
         return response.json() as IStudentCourse;
      }).subscribe(course => {
         this.studentCourse.next(course);
      });
    }
}

export interface IStudentCourse {
  id: string,
  refNo: string;
  student: string;
}

并且在您的 template 中使用 Angular async 管道自动订阅持有数据的 Observable。

Plunker