Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting [object Object] after getting http response using subscribe in Angular 2

ProductService.ts

   getProduct(id: number): Observable<IProduct> {

    return this._http.get(this._productUrl + '/GetById/' + 
           id).map((response: Response) => <IProduct>response.json())           
        .catch(this.errorHandler);     
}

ProductDetailComponent.ts

   getProduct(id: number) {
    this._productService.getProduct(id).subscribe(
        res => {               
            console.log('before component ' + res);     
            this.product = res;
            console.log('after component ' + res);                
        },
        error => this.errorMessage = <any>error),
        console.log('execution complete'); 
}

When receiving result in subscribe it is coming as
execution complete, before component [object Object], after component [object Object]

like image 532
Lovepreet Singh Avatar asked Aug 02 '26 06:08

Lovepreet Singh


2 Answers

You need to do JSON.stringify

console.log('before component ' + JSON.stringify(res));  
like image 180
Sajeetharan Avatar answered Aug 04 '26 01:08

Sajeetharan


You are using string concatenation (using the + sign). This way, Javascript will first convert the Object to a string ([object Object]). If you don't want that, you could try it like this: console.log('before component', res).

Note the comma, not a +. This passes the object to console.log as a separate parameter, allowing your browser or CLI to do the rendering. For instance, this way (in the browser) you can expand or collapse the object.

like image 32
Jeff Huijsmans Avatar answered Aug 04 '26 00:08

Jeff Huijsmans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!