i have mentioned in comments when i console log the selected property with in ngOnInit
it does console the object, however outside of this block this when i console this property it is undefined. can some on help how to get it work.. or any other solution
import { Product } from './../../Models/ProductModel';
import { Component, OnInit } from '@angular/core';
// import { Subscription } from "rxjs/Rx";
import 'rxjs';
import { Router, ActivatedRoute } from '@angular/router';
import { ProductService } from 'app/products/product.service';
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html',
styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
public selectedProduct: Product;
private productIndex: string;
// private subscription: Subscription;
constructor(private router: Router,
private route: ActivatedRoute,
private PService: ProductService) { }
ngOnInit() {
this.route.params.subscribe(
(params: any) => {
this.productIndex = params['id'];
}
);
this.PService.getProduct(this.productIndex).subscribe((data: any) =>{
// return the object
console.log(data.product)
return this.selectedProduct = data.product,
//output the here object
console.log(this.selectedProduct);
}
);
// output undefined
console.log(this.selectedProduct);
}
this is the getProduct method in my service
getProduct(id:string){
const headers = new Headers({ 'Content-Type': 'application/json' });
return this.http.get('http://localhost:3000/products/'+id, { headers : headers})
.map((response: Response) => response.json())
.catch( (error: any) =>
{
this.ErS.getError(error.json());
return Observable.throw(error);
})
}