Angular2无法从rest api获取json

时间:2016-11-03 16:59:28

标签: angular typescript spring-boot

I tried to follow tutorial on angular.io (Tour the Heroes) Unlike in tutorial i tried to make GET request on locally deployed springboot application for which i couldnt get the hero's list on my angular app. (Same works with URL using in-memory-dataservice)

来自我的API的JSON响应:

[{"id":11,"name":"Mr. Nice"},{"id":12,"name":"Narco"}]

我的代码如下所示(仅更改为教程是URL):

private heroesUrlmain = 'http://localhost:8080/heros.json';  // URL to web api

private headers = new Headers({'Content-Type': 'application/json'});

constructor(private http: Http) { }

getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrlmain)
  .toPromise()
  .then(response => response.json().data as Hero[])
  .catch(this.handleError);
 }

为了服务我只导入一些基本的东西:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
import 'rxjs/Rx';

请问您需要更正的建议更改,以便有角度的应用可以使用get方法从API获取数据。

添加@component:

@Component code:

import { Component } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { Router } from '@angular/router';

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

@Component({
  moduleId: module.id,
  selector: 'my-heroes',
  templateUrl: 'heroes.component.html',
  styleUrls: [ 'heroes.component.css' ]
})

export class HeroesComponent implements OnInit {
  heroes: Hero[];
  selectedHero: Hero;

  constructor(
    private router: Router,
    private heroService: HeroService) { }

  getHeroes(): void {
    this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  }

  ngOnInit(): void {
    this.getHeroes();
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }    
}  

模板:

<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes" (click)="onSelect(hero)"
      [class.selected]="hero === selectedHero">
    <span class="badge">{{hero.id}}</span>
    <span>{{hero.name}}</span>
    <button class="delete"
            (click)="delete(hero); $event.stopPropagation()">x</button>
  </li>
</ul>
<div *ngIf="selectedHero">
  <h2>
    {{selectedHero.name | uppercase}} is my hero
  </h2>
  <button (click)="gotoDetail()">View Details</button>
  <label>Hero name:</label> <input #heroName />
  <button (click)="add(heroName.value); heroName.value=''">
    Add
  </button>
</div>

根据评论询问的错误代码。

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

1 个答案:

答案 0 :(得分:0)

您的JSON是一个数组。数组没有任何名为data的字段。然而你正在做response => response.json().data as Hero[]

您只需要response => response.json() as Hero[]