简体   繁体   中英

Angular 6 sharing data between components not updating the array

In angular 6, I am trying to achieve, when user navigate to other page, pass ID using localstorage instead of url params. I have ProductList, ProductDetails components and ProductService. On ProductList page, when user clicks on view product, it should redirect to ProductDetails page with ID stored in the localstorage. On ProductDetails component's ngOnInit(), i am calling get method from service, but it returning old array, not updated array.

ProductList component

//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 component

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 component

 data:any = [];

 ngOnInit(){
    this.productService.productUpdatedListener().subscribe(productData => {
   this.data = productData;
    })
 }

here in this.data, Whenever i navigate to this details page, I get old array. For example, In ProductList, when i click on product ID 123, it navigates to ProductDetails page and showing ID 123 in array, but again from ProductDetails page, when I click on another product, lets say ID 124, it navigates to ProductDetails page but showing old value 123 in array. I tried many approaches but unable to solve it. What i am missing? Thank you

你应该使用BehaviorSubject而不是Subject:

private productUpdated = new BehaviorSubject<any>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM