ng2 Get Object from HttpGet Service

巧了我就是萌 提交于 2019-12-11 01:35:14

问题


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.

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

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

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.

Updated: plnkr Link

I prefer to put this HttpGet service in the separate service file because I need to use it in other components too.


回答1:


see plunker : plunker

in your template use ?:

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

    }



回答2:


You are returning a n Observable of your model which is empty at that time. It is async.

try this:

getStudentCourse(): Observable<IStudentCourse>: {
    return this.http.get('/api/student/getstudentcourse')
        .map(result => result.json() as IStudentCourse)        
        .catch(() => throw 'Could not load data.');

}

See this plunker




回答3:


You could use a BehaviorSubject for this task and in your Http Subscription emit a new value for the Subject.

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

And in your template use Angular async Pipe to auto subscribe to the Observable holding the Data.

Plunker



来源:https://stackoverflow.com/questions/42905990/ng2-get-object-from-httpget-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!