[英]angular 4 observable returns [object Object]
我使用Angular 4作為我的前端,使用Laravel 5.5作為我的靜態API。 后端看起來很好,可以解決問題,我可以發送curl請求並完全返回我期望的值,一個帶有2個鍵值對的JSON:
[{"id":1,"name":"Mr. Nice"}]
當我嘗試使用角度進行此操作時,我得到以下信息:
HERO: [object Object] 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>
班級:
export class Hero {
id: number;
name: string;
}
由於某種原因,我可以說是angular沒有將json識別為Hero類的單個實例,因此模板中的*ngIf=
確實被觸發了。 服務中的getHeroes
函數可以正常工作,它返回多個條目,並且我在模板中遍歷它們,是否有明顯的東西我丟失了?
我對angular還是比較陌生,因此不勝感激。
謝謝。
您收到的是數組內的一個對象,該[object Object]
在您的視圖中導致[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}`))
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.