我使用角4作为我的前端和Laravel5.5作为我的restful。后端看起来很好,wrt问题,我可以发送curl请求并得到我所期望的,一个带有两个键值对的JSON:
[{"id":1,"name":"Mr. Nice"}]
当我试着用角度来做这件事时,我会得到以下信息:
HERO: [object Object] HERO.ID: HERO.NAME
我的服务(我包括了一个工作上的get请求,仅供参考):
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl).pipe(
tap(heroes => this.log(`fetched heroes, ${this.heroesUrl}`)),
catchError(this.handleError('getHeroes', []))
);
}
/** ISSUE HERE */
getHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`;
return this.http.get<Hero>(url).pipe(
tap(_ => this.log(`fetched hero id=${id}, ${url}`)),
catchError(this.handleError<Hero>(`getHero id=${id}`))
);
}构成部分:
import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { HeroService } from '../hero.service';
import { Hero } from '../hero';
@Component({
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) {}
ngOnInit(): void {
this.getHero();
}
getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.location.back();
}
}模板:
<div *ngIf="hero">
<div>HERO: {{ hero }} HERO.ID: {{ hero.id }} HERO.NAME {{ hero.name }}</div>
<h2>{{hero.name | uppercase}} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
<label>name:
<input [(ngModel)]="hero.name" placeholder="name">
</label>
</div>
</div>
<button (click)="goBack()">go back</button>全班:
export class Hero {
id: number;
name: string;
}据我所知,由于某种原因,角不能将json识别为类Hero的单个实例,模板中的*ngIf=确实会被触发。服务中的getHeroes函数工作,它返回多个条目,我在模板中循环它们,是否有相当明显的东西是我遗漏的?
我很新的角度,所以任何帮助都将不胜感激。
谢谢。
发布于 2017-11-27 04:45:27
您正在接收的是数组中的一个对象,这将导致视图中的[object Object]。你想要的是从你的反应中提取出一个英雄:
getHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`;
return this.http.get<Hero[]>(url).pipe(
map(heroes => heroes[0]) // here!
tap(_ => this.log(`fetched hero id=${id}, ${url}`)),
catchError(this.handleError<Hero>(`getHero id=${id}`))
);
}https://stackoverflow.com/questions/47495583
复制相似问题