2016-08-18 55 views
1

我有一個從服務調用函數的組件。將使用http的角度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

相關問題