繁体   English   中英

角度4可观察到的回报[object Object]

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM