angular 4 observable returns [object Object]

612
November 26, 2017, at 10:26 PM

I am using Angular 4 as my frontend and Laravel 5.5 as my restful API. the backend seems fine wrt the problem, i can sent curl requests and get back exactly what i expect, a JSON with 2 key-value pairs:

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

When i try and do this with angular i get the following:

HERO: [object Object] HERO.ID: HERO.NAME

my service (I included a working get request just for reference):

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}`))
    );
}

the component:

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();
    }
}

the template:

<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>

the class:

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

From what i can tell for some reason angular is not recognizing the json as a single instance of the class Hero, the *ngIf= in the template does get triggered. the getHeroes function in the service works, it returns a multiple entries and i loop through them in the template, is there something fairly obvious that i am missing?

I am fairly new to angular so any help would be appreciated.

Thanks.

Answer 1

Also add map function into the pipe function.

getHero(id: number): Observable<Hero> {
    const url = `${this.heroesUrl}/${id}`;
    return this.http.get<Hero>(url).pipe(
        map(response => response.json()),
        tap(_ => this.log(`fetched hero id=${id}, ${url}`)),
        catchError(this.handleError<Hero>(`getHero id=${id}`))
    );
}
Rent Charter Buses Company
READ ALSO
How to use imacros to reload recaptcha frame to load new captcha?

How to use imacros to reload recaptcha frame to load new captcha?

I need to use imacros to reload recaptcha frame in this image to load new captcha, everyone, plz help: Link to the captcha: https://wwwmytrainerrewards

341
Javascript: Changing a boolean in an else if statement

Javascript: Changing a boolean in an else if statement

i am having the following problemI am trying to do this but it is not working:

245
createjs calculate bounds of circular sector

createjs calculate bounds of circular sector

I create a circular sector manually, so I know the starting boundsAfter that, the user can rotate the sector using as regX-regY the center (of the circle), so I move temporarily the center

281