【问题标题】:Angular2 unable to fetch json from rest apiAngular2无法从rest api获取json
【发布时间】:2016-11-03 16:59:28
【问题描述】:
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';

能否请您建议我需要更正的更改,以便 Angular 应用程序可以使用 get 方法从 API 获取数据。

添加@组件:

@组件代码:

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

【问题讨论】:

  • 错误是什么?
  • @Sefa Ümit Oray:没有错误消息,但在我的 Angular 应用程序中没有在网页中显示英雄
  • 这取决于您的组件和模板代码。请编辑您的问题以及组件和模板代码。
  • @Sefa Ümit Oray:我已在我的问题中添加了组件代码。
  • @RakeshMothukuri 但您还没有发布您的模板。此外,您是否检查了开发工具的网络面板以验证您收到的 JSON 是否符合问题中发布的 JSON? this.handleError() 是做什么的?

标签: angular typescript spring-boot


【解决方案1】:

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

你只需要response =&gt; response.json() as Hero[]

【讨论】:

  • 我尝试从代码中的“response.json().data”中删除 .data 并启动了 npm,但问题仍然存在。
猜你喜欢
  • 2018-10-25
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-01
  • 2019-08-26
相关资源
最近更新 更多