2016-08-18 12 views
1

サービスから関数を呼び出すコンポーネントがあります。httpをコンポーネントに使用するangle 2サービスからのデータを渡します。

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

サービスでは、私はサブスクライブでhttpコールを持っています。私はhttpリクエストの結果を自分のコンポーネントに戻したい。

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

私はangular2を初めて使っています。私はコンポーネントにhttpリクエストの結果として返された製品変数を欲しいです。しかしにconsole.logを与えながら、観察可能なオブジェクトが出て、私の応答データ

+1

使用観測およびコンポーネントでそれらを購読してください。 https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service –

答えて

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

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

とコンポーネント内に戻っている:サービスで

constructor(private productService: ProductService) {} 

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

ありがとうございました。 – Varada

+0

問題ありません!これを答えにすることを忘れないでください;) –

+0

@ stijn.aertsサービスに加入すればどうなりますか?コンポーネント内のデータをどのように返すことができますか? – Sanket

関連する問題