[英]Angular 6 sharing data between components not updating the array
在角度6中,我试图实现当用户导航到其他页面时,使用localstorage而不是url参数传递ID。 我有ProductList,ProductDetails组件和ProductService。 在“产品列表”页面上,当用户单击查看产品时,应重定向到ID存储在本地存储中的“产品详细信息”页面。 在ProductDetails组件的ngOnInit()上,我从服务中调用get方法,但它返回的是旧数组,而不是更新后的数组。
ProductList组件
//when user click on view product
goToProduct(id) {
this.productService.setProductParams({
routeName:'product-details', //here i am taking name bcz i want to store all routes ID for history purpose
data: { productId: id }
});
this.router.navigate(['/product-details']);
ProductService组件
productData:any = [];
private productUpdated = new Subject<any>();
constructor() { //get data from local storage }
setProductParams(data) {
//Check whether current route name exist or not
if (this.productData.filter(e => e.routeName === data.routeName).length > 0) {
//Get index of existed route
const index = this.productData.map(function (route) { return route.routeName; }).indexOf(data.routeName);
//Update product data by index
this.productData[index].data = data.data;
this.productUpdated.next(this.productData);
//Set data to localstorage
-------
} else {
this.productData.push(data);
this.productUpdated.next(this.productData);
//Set data to localstorage
-------
}
getProductParams() {
this.productUpdated.next(this.productData);
return this.productData;
}
productUpdatedListener() {
return this.productUpdated.asObservable();
}
ProductDetails组件
data:any = [];
ngOnInit(){
this.productService.productUpdatedListener().subscribe(productData => {
this.data = productData;
})
}
在this.data中,每当我导航到此详细信息页面时,都会得到旧数组。 例如,在ProductList中,当我单击产品ID 123时,它导航到ProductDetails页面并以阵列形式显示ID 123,但是再次从ProductDetails页面中,当我单击另一个产品时,说ID 124,它导航到ProductDetails页面,但是在数组中显示旧值123。 我尝试了许多方法,但无法解决。 我想念的是什么? 谢谢
你应该使用BehaviorSubject而不是Subject:
private productUpdated = new BehaviorSubject<any>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.