2017-08-15 70 views
1

我有一個network.service.ts和代碼如下 -角4 HTTP服務調用不返回數據

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

我的同行list.component.ts是組件文件。

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

當調用ngOnInit方法時,this.peers始終設置爲undefined。數據從服務器返回,但回調無法將數據設置爲this.peers變量。有人可以幫我嗎?

謝謝。

+0

「角度2/4」的正確標籤是「角度」。標籤'angularjs'用於'angular'版本1.x(即js/javascript版本)。 – Igor

回答

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

應該

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

呼叫json()將直接返回有效載荷/數據。你可能想要做.data的唯一原因是你的json結果中有一個名爲data的實際屬性/字段。