我使用 Angular 4 作为我的前端,使用 Laravel 5.5 作为我的 Restful API。后端似乎很好地解决了这个问题,我可以发送curl请求并准确地返回我所期望的,一个带有2个键值对的JSON:
[{"id":1,"name":"尼斯先生"}]
当我尝试使用 Angular 执行此操作时,我得到以下结果:
HERO:[对象对象] HERO.ID:HERO.NAME
我的服务(我包含了一个工作获取请求仅供引用):
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>
类(class):
export class Hero {
id: number;
name: string;
}
据我所知,出于某种原因,Angular 无法将 json 识别为 Hero 类的单个实例,模板中的 *ngIf=
确实会被触发。服务中的 getHeroes 函数有效,它返回多个条目,我在模板中循环遍历它们,是否有一些相当明显的东西我丢失了?
我对 Angular 还很陌生,因此我们将不胜感激。
谢谢。
最佳答案
您收到的是数组中的一个对象,这会导致您的 View 中出现[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}`))
);
}
关于javascript - Angular 4可观察返回[对象对象],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47495583/