如何在一个组件中运行 http get 后,使用 Subject 和 next 更新另一个组件中的数据



我的服务器正在使用Angular和Express。我希望我的产品组件在 admin.component 中编辑或输入新产品后刷新。通过将 shopping.service 与 Subject 一起使用并在第 125 行的 admin.component 中添加 next,并在 product.compoent 中的构造函数中订阅,我能够让它部分工作,但我得到了一个奇怪的行为:有时在我第一次编辑产品时页面会更新,但在第二次我编辑它时它不会,反之亦然。

谢谢

GitHub 上的项目 https://github.com/YehonatanGitHub/eCommerce

产品组件:

import { DataService } from 'src/app/shared/data.service';
import { Product } from './product.model';
import { ShoppingService } from '../../shopping.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css'],
})
export class ProductComponent implements OnInit {
public loadedProducts = [];
private refreshSub: Subscription;
private getDataSub: Subscription;
constructor(private dataService: DataService, private shoppingService: ShoppingService) {
this.refreshSub = this.shoppingService.refreshProducts.subscribe(() => {
console.log("getallproducts");
this.ngOnInit();
});
}
ngOnInit() {
this.getAllProducts();
}
ngOnDestroy(): void {
this.refreshSub.unsubscribe();
this.getDataSub.unsubscribe();
}
private getAllProducts() {
this.getDataSub = this.dataService.fetchProducts()
.subscribe((data) => this.loadedProducts = data);
}
clickEditProduct(editProduct: Product) {
console.log(editProduct);
this.shoppingService.statuseEditProduct.next(editProduct);
}}     

admin.component:

onSubmit(postData: Product) {
if (this.editProduct == undefined) {
console.log("NEW product sent to POST");
this.newProduct = postData;
this.http.post('http://localhost:3000/admin/add-product', postData)
.subscribe(responseData => {
console.log(responseData);
});
this.productForm.setValue({
proname: "",
price: "",
picture: "",
category: ""
});
this._opened = false;
} else {
let productEditInfo = {
_id: this.editProduct._id,
proname: postData.proname,
price: postData.price,
picture: postData.picture,
category: postData.category
}
console.log(productEditInfo);
this.http.post('http://localhost:3000/admin/edit-product', productEditInfo)
.subscribe(responseData => {
console.log(responseData);
});
console.log("Edit product sent");
this.productForm.setValue({
proname: "",
price: "",
picture: "",
category: ""
});
this.editProduct = undefined;
this._opened = false;
}
this.shoppingService.refreshProducts.next();
}
} 

购物服务


import { Injectable } from '@angular/core';
import { Product } from '../shopping/products/product/product.model';
import { Subject } from 'rxjs'
@Injectable()
export class ShoppingService {
statuseEditProduct = new Subject<Product>();
refreshProducts = new Subject<void>();
constructor() { }
} 

>您在onSubmit方法中调用this.shoppingService.refreshProducts.next();,而无需等待产品实际保存。因此,产品组件在服务发送保存产品的请求后立即发送刷新请求。因此,请求由您的服务器并发处理。因此,有时刷新请求会看到更新/创建的产品,有时不会。

要解决此问题,请仅在收到对创建/更新请求的响应后要求产品组件进行更新。

最新更新