[英]Getting data from service in component in Angular 2
So I created a component where it handles products. 因此,我创建了一个用于处理产品的组件。
ngOnInit(){
this.products = [];
this.products = this.product.all();
}
In my services class I am retrieving the products in the constructor and retrieving it through the all method. 在我的服务类中,我将在构造函数中检索产品,并通过all方法对其进行检索。
constructor(private http: Http, private admin: AdminService){
admin.getProduct(function(response){
this.products = response.data;
}.bind(this));
}
all(): any{
return this.products;
}
This issue with this is that the all method is run before the products arrive. 这样做的问题是,all方法在产品到达之前就已运行。 Is there anyway I can get the service class to load the products and be able to retrieve the products back in my component?
无论如何,我可以获得服务类来加载产品并能够将产品取回组件中吗?
Here's a suggestion using RxJS: 这是使用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
}
And the component: 和组件:
ngOnInit(){
this.products = [];
this.product.all().subscribe((products) => { // changed this line
this.products = products; // added this line
}); // added this line
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.