我正在为服务器使用Angular和Express。我想在编辑或在admin.component中输入新产品后刷新product.component。通过使用带有Subject的shopping.service并在第125行的admin.component中添加next并在product.compoent中订阅了构造函数,我能够使其部分工作,但是我遇到了奇怪的现象:有时在第一个当我编辑产品时,页面会更新,但是在第二次编辑时,页面不会更新,反之亦然。
谢谢
在github https://github.com/YehonatanGitHub/eCommerce上的项目
product.component:
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();
}
}
ShoppingService
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() { }
}
答案 0 :(得分:0)
您正在使用this.shoppingService.refreshProducts.next();
方法调用onSubmit
,而无需等待实际保存产品。因此,产品组件在服务发送了保存产品的请求后立即发送刷新自身的请求。这样,请求将由您的服务器同时处理。因此,有时刷新请求将看到更新/创建的产品,有时则看不到。
要解决此问题,仅在收到对创建/更新请求的响应后,才要求产品组件进行更新。