简体   繁体   English

Angular 4 http服务调用不返回数据

[英]Angular 4 http service call does not return data

I have a network.service.ts and the code is below - 我有一个network.service.ts,代码如下-

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. 我的peer-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);
  }
}

When the ngOnInit method is invoked, this.peers is always set as undefined. 调用ngOnInit方法时,this.peers始终设置为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. 正在从服务器返回数据,但是回调无法将数据设置为this.peers变量。 Can someone help me out? 有人可以帮我吗?

Thanks. 谢谢。

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

should be 应该

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

The call json() will return the payload/data directly. 调用json()将直接返回有效负载/数据。 The only reason you might want to do .data is if there is an actual property/field in your json result named data . 您可能要执行.data的唯一原因是,在json结果中有一个名为data的实际属性/字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM