Search code examples
htmljsonangularangular2-services

Undefined Object but I got something in console log


I am trying to access product.img_url but an error tells me it is undefined. When I tried to use console log, it clearly shows that my product object has a value. Can anyone help me in this?

product.component.ts

export class ProductComponent implements OnInit{
    product: Products;

    constructor(private _router: Router, private _productsService: ProductsService){}

    ngOnInit(){
        var str = this._router.url;
        var param = str.split("/");
        this._productsService.getProductById(param[2], param[3])
            .subscribe((product) => {this.product = product; console.log(product);}),
            (err) => console.log(err);
    }

}

HTML div

            <div class="tab-content">
                <div class="tab-pane active" id="product-page1" [hidden]="product">
                    <img src="{{product.img_url}}" alt="..."/>
                </div>
            </div>

Error stack trace

enter image description here

console.log output

enter image description here


Solution

  • Ok I already found out the problem here.

    The object becomes an array after I get it therefore I need to put [0] when accessing the index of the array in HTML. The code looks like this.

    <img src="{{product[0].img_url}}" alt="..."/>