从Angular 2中的组件中获取服务数据

时间:2017-06-12 19:27:13

标签: angular

所以我创建了一个处理产品的组件。

ngOnInit(){
   this.products = [];
   this.products = this.product.all();
}

在我的服务类中,我正在检索构造函数中的产品并通过all方法检索它。

constructor(private http: Http, private admin: AdminService){
   admin.getProduct(function(response){
     this.products = response.data;
   }.bind(this));
}

all(): any{
   return this.products;
}

这个问题是all产品在产品到货之前运行。无论如何我可以获得服务类来加载产品并能够在我的组件中检索产品吗?

1 个答案:

答案 0 :(得分:1)

以下是使用RxJS的建议:

productsChange = new Subject();                   // added this line
constructor(private http: Http, private admin: AdminService){
   admin.getProduct(function(response){
     this.productsChange.next(response.data);     // changed this line
   }.bind(this));
}

all(): Observable<any> {                          // changed the return type
   return this.productsChange;                    // changed this line
}

组件:

ngOnInit(){
   this.products = [];
   this.product.all().subscribe((products) => {   // changed this line
       this.products = products;                  // added this line
   });                                            // added this line
}