【发布时间】:2019-08-07 20:29:30
【问题描述】:
在 Angular 6 中,我试图实现,当用户导航到其他页面时,使用 localstorage 而不是 url 参数传递 ID。我有 ProductList、ProductDetails 组件和 ProductService。在 ProductList 页面上,当用户点击查看产品时,它应该重定向到 ProductDetails 页面,ID 存储在本地存储中。在 ProductDetails 组件的 ngOnInit() 上,我正在从服务调用 get 方法,但它返回的是旧数组,而不是更新的数组。
产品列表组件
//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。我尝试了很多方法,但无法解决。我错过了什么?谢谢
【问题讨论】:
标签: javascript angular rxjs observable