mr_plutus2016-09-23 20:34:05
mr_plutus, 2016-09-23 20:34:05

Angular2, what is the error when requesting restApi?

Hi all. I can’t figure out why it doesn’t show data
A couple of points:
- The server sends data in the form of json
- I know what to transfer to a separate file, receiving data, for now everything is in component for tests
Component code,:

import {Component, OnInit} from '@angular/core';
import {Http, Headers, URLSearchParams, Response} from '@angular/http';
import 'rxjs/Rx';
import {GlobalVariable} from './../../app.config'
import {Observable}     from 'rxjs/Observable';

    templateUrl: './template.html',

export class RegistriesComponent implements OnInit{
    errorMessage: string;

    constructor(private http: Http) {}
    private urlApi = GlobalVariable.BASE_API_URL;

    ngOnInit() {
                res => this.data = res,
                error =>  this.errorMessage = <any>error,

    getHeroes (): Observable<Array<any>> {
        return this.http.get(this.urlApi + 'rest/nsi/routes')

    private extractData(res: Response) {
        let body = res.json();
        return body.data || { };

    private handleError (error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        return Observable.throw(errMsg);

Output in the template:
<tr *ngFor="let item of data">

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Ruslan Lopatin, 2016-09-25

Show the data that comes from the server.
Is there a "data" field in the response? This is exactly an array of objects containing the "number" field. If so, why is the extractData() method returning an object rather than an array instead of an array? It should probably be like this:

private extractData(res: Response): Array<{"number": any}> {
  return res.json().data || [];

mr_plutus, 2016-09-27

I tested it on a plunker and it works... I don't even know where to dig...

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

import 'rxjs/Rx';

    templateUrl: 'template.html',
    providers: [ HeroService ]
export class RegistriesComponent implements OnInit {
    errorMessage: string;
    public data: Array<any> = [
    constructor (private heroService: HeroService) {}

    ngOnInit() {
        this.data = [

    getHeroes() {
            data => this.data = data,
            error =>  this.errorMessage = <any>error))


In the console from the subscriber it says:
Naturally display test2, everything is OK on the plunker, the data is output from the server

nuclear_kote, 2016-09-27

Just for the future. As for me, it is better to use ng2-resource-rest for rests (an analogue of ngResource from the 1st Angular)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question