2

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

1 Answer 1

3
@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)
    )
}
Sign up to request clarification or add additional context in comments.

2 Comments

No problem! Don't forget to mark this as the answer ;)
@stijn.aerts What if we subscribe in service ? How can we return the data in component ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.