ng2从HttpGet服务获取对象

时间:2017-03-20 14:18:05

标签: angular typescript angular2-services

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

我想在我网站的主页登陆页面上显示学生和课程数据。目前,我的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);
    }
}

您可以在我的屏幕截图中看到studentCourse中的ngOnInit始终为空,我无法将其绑定。

你可以帮我解决这个错误吗?感谢。

已更新: plnkr Link

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

3 个答案:

答案 0 :(得分:2)

您正在返回当时为空的模型的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

答案 1 :(得分:1)

您可以使用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 Pipe来自动订阅包含数据的Observable。

Plunker

答案 2 :(得分:0)

请参阅plunkerplunker

模板中的

使用?

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

    }