Angular 2 Can’t get data from Rest Service

梦想的初衷 提交于 2020-01-25 21:10:34

问题


I’m new in Angular 2 and I’m playing with the environment to create some app. Doing the things like the site Angular.io says I’m able to create an Injectable Service and using it on my AppComponent but only If I read the data from the same .ts file like this.sourceData = {…}. If I get the json data from a Rest service the data is undefined

app.service.ts

Import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class WebService {
    private dataUrl = 'http://localhost:8080/api/home';
    constructor(private http: Http) { }
    getData() : Observable<any> {
        return this.http.get(this.dataUrl)
            .map(this.extractData)
            .catch(this.handleError);
   }
    private extractData(res: Response) {
        let body = res.json();
        return body.data || {};
    }

app.component.ts

import { Component, OnInit } from '@angular/core';
import { WebService } from './app.service';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [WebService]

})
export class AppComponent implements OnInit {
    errorMessage: string;
    theData: Object;
    constructor(private dataService: WebService) {}

    ngOnInit() { this.getDataFromService(); }
    getDataFromService() {
        this. dataService. getData ()
            .subscribe(
            myData => this.theData = myData,
            error => this.errorMessage = <any>error);
    }    
}

app.component.html

<p> {{ theData. classroom.Id }}</p>

JSON from service

{
    "classroom": {
        "Id": "01",
        "totalStudents": "2",

        "Students": [{
            "Name": "Jhon",
            "age": "18"
        }, {
            "Name": "Doe",
            "age": "18"
        }],
        "Teachers": [{
            "Name": "Jane",
            "age": "38"
        }, {
            "Name": "Doe",
            "age": "35"
        }]
    }
}

Am I missing something when using Observables? Thanks in advance


回答1:


When you call response.json(), it automatically grabs the data property from the ajax response and returns it, so remove your reference to .data in your extractData method.

getData() : Observable<any> {
        return this.http.get(this.dataUrl)
            .map(this.extractData)
            .catch(this.handleError);
   }
    private extractData(res: Response) {
        return res.json();
        //return body.data || {};  // <-- this line needs to go
    }

FYI, because your extractData method is reduced to one line, most example (and real life) code will just inline that call in your map function

 getData() : Observable<any> {
        return this.http.get(this.dataUrl)
            .map(response => response.json())
            .catch(this.handleError);
   }


来源:https://stackoverflow.com/questions/43059415/angular-2-can-t-get-data-from-rest-service

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