我正在使用angular2处理简单的CRUD应用程序。我ProductListComponent
显示了产品列表,此组件还有两个子组件ProductDetailComponent
和ProductUpdateComponent
。
ProductUpdateComponent
会打开模式并提交表单,成功提交后我会导航到ProductListComponent
。因此,在我导航到ProductListComponent
后成功更新后,视图未使用新数据进行更新(产品列表未更新)
ProductListComponent
@Component({
selector: 'product-list',
moduleId: module.id,
templateUrl: 'product-list.component.html',
directives: [ProductDetailComponent, ProductUpdateComponent],
providers: [ProductService]
})
export class ProductListComponent {
public products: any;
constructor(private productService: ProductService) {
this.productService.getAllProducts()
.subscribe(
response => this.products = response.products
);
}
}
ProductUpdateComponent
Component({
selector: 'product-form',
moduleId: module.id,
templateUrl: 'product-form.component.html',
providers: [CheckFormErrors, ProductService]
})
export class ProductFormComponent {
productForm: ControlGroup;
formFields: Array<string>;
view: string;
@Input()
pr: Product;
// form stuff goes here
// after form submitted
saveProduct() {
if (this.productForm.dirty && this.productForm.valid) {
let form = this.productForm.value
let formProduct = new Product({
code: form.code,
name: form.name,
price: form.price,
packing: form.packing,
description: form.description
});
this.productService.updateProduct(this.pr, formProduct)
// navigate to ProductList
this.router.navigate(['/']);
console.log("competed")
}
}
请在此查看详细的完整代码: https://bitbucket.org/asifpy/inventory-manager/src
答案 0 :(得分:0)
您的代码没有正确构建。 看看这段代码:
saveProduct() {
if (this.productForm.dirty && this.productForm.valid) {
let form = this.productForm.value
let formProduct = new Product({
code: form.code,
name: form.name,
price: form.price,
//stock: form.stock,
packing: form.packing,
description: form.description
});
if(this.pr){
this.productService.updateProduct(this.pr, formProduct)
}
else{
this.productService.addProduct(formProduct)
}
this.router.navigate(['/']);
console.log("competed")
}
}
您的代码在导航之前不会等待http调用结束。 但你不需要导航。您需要在响应时刷新产品模型。为了快速修复,更改添加和更新功能以返回http observable,订阅它们并在回拨时执行您的路由。