2
votes

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

1
Use observables in the service and subscribe to them in the component. See also angular.io/docs/ts/latest/cookbook/… - Günter Zöchbauer

1 Answers

3
votes
@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)
    )
}