簡體   English   中英

ng2從HttpGet服務獲取對象

[英]ng2 Get Object from HttpGet Service

我正在嘗試從WebAPI中獲取JSON數據,但它不起作用。 每當我嘗試在組件中使用該返回對象時,我總是會變得undefined

我想在我的網站的首頁登錄頁面上顯示學生和課程數據。 此刻,我的控制器/ 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數據,並且可以在“網絡流量”中看到它,也可以在控制台中看到它。

在此處輸入圖片說明

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

您可以在屏幕截圖中看到,在ngOnInit中, studentCourse始終為null,而我無法將其綁定。

您能幫我解決這個錯誤嗎? 謝謝。

更新: plnkr鏈接

我更喜歡將此HttpGet服務放在單獨的服務文件中,因為我也需要在其他組件中使用它。

您將返回當時為空的模型的Observable。 這是異步的。

嘗試這個:

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

}

看到這個矮人

您可以將BehaviorSubject用於此任務,並在Http Subscription中為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;
}

並在template使用Angular async管道自動訂閱包含數據的Observable。

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

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM