angular 4个可观察returns [对象对象]

angular 4 observable returns [object Object]

我使用 Angular 4 作为我的前端,Laravel 5.5 作为我的 restful API。后端似乎没有问题,我可以发送 curl 请求并准确返回我期望的结果,一个 JSON 和 2 个键值对:

[{"id":1,"name":"Mr. Nice"}]

当我尝试使用 angular 执行此操作时,我得到以下信息:

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>

class:

export class Hero {
    id: number;
    name: string;
}

据我所知,出于某种原因 angular 没有将 json 识别为 class Hero 的单个实例,模板中的 *ngIf= 确实被触发。服务中的 getHeroes 功能有效,它 returns 有多个条目,我在模板中循环遍历它们,是否有一些明显我遗漏的东西?

我是 angular 的新手,所以如果有任何帮助,我们将不胜感激。

谢谢。

您收到的是一个数组中的对象,这导致您认为 [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}`))
    );
}