Varada Varada - 3 months ago 9
HTTP Question

pass a data from angular 2 service that uses http to a component

I have a component that calls a function from a service.

export class ZoomComponent {
constructor(private productService: ProductService){}
container: any;
product:ProductObj[];
ngOnInit() {
this.product = this.productService.getProduct()
}
}


In the service I have an http call with subscribe. I want the result from the http request retuned to my component.

@Injectable()
export class ProductService {

product:ProductObj[];
constructor(private http: Http) { }

getProduct() {
return this.http.get('./friends.json').map((res:Response) => res.json()) .subscribe(
data => this.product = data
//function(data){console.log(data)}
)
}
}


I am new to angular2. I want the product variable returned as the result of the http request on my component. But while giving a console.log, the observable object is returning with out my response data

Answer
@Injectable()
export class ProductService {   
    constructor(private http: Http) { }

    getProduct() {         
       return this.http.get('./friends.json')
         .map((res:Response) => res.json())     
    }   
}

And in component:

constructor( private productService: ProductService) {}

ngOnInit() {
    this.productService.getProduct().subscribe(
       data => console.log(data)
    )
}