Search code examples
angularangular2-services

Angular 4 http service call does not return data


I have a network.service.ts and the code is below -

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

import { Peer } from '../model/Peer';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class NetworkService {
    private apiURL = 'http://127.0.0.1:8080/organization/';

    constructor(private http: Http) { }

    public getOrganizationPeers(organizationName): Promise<Peer[]> {
        return this.http.get(this.apiURL + organizationName + '/peers')
            .toPromise()
            .then((response) => response.json().data as Peer[])
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

My peer-list.component.ts is the component file.

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

import { NetworkService } from './network.service';

import { Peer } from '../model/Peer';

@Component({
  selector: 'another',
  templateUrl: './peer-list.template.html'
})

export class PeerListComponent implements OnInit {

  private peers: Peer[];
  constructor(private networkService: NetworkService) { }

  ngOnInit(): void {
      console.log('test');
      this.networkService.getOrganizationPeers('peerOrg1').then(peers 
=> this.peers = peers);
  }
}

When the ngOnInit method is invoked, this.peers is always set as undefined. The data is getting returned from the server, but the call back is not able to set the data to the this.peers variable. Can someone help me out?

Thanks.


Solution

  • .then((response) => response.json().data as Peer[])
    

    should be

    .then((response) => response.json() as Peer[])
    

    The call json() will return the payload/data directly. The only reason you might want to do .data is if there is an actual property/field in your json result named data.