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 코드 :
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>
는 handleError 코드입니다.
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
는 오류가 무엇을해야합니까? – Sefa
@Sefa Ümit Oray : 오류 메시지가 없습니다. 내 각형 앱에 웹 페이지에 히어로가 표시되지 않습니다. –
이는 구성 요소 및 템플릿 코드에 따라 다릅니다. 질문, 구성 요소 및 템플릿 코드를 수정하십시오. – Sefa