正如标题所说。之间有什么区别
public addNewProduct() {
if (this.f.valid) {
this.product.count = 1;
this.productService.saveProduct(this.product).subscribe((data) => console.log('product added or updated'));
}
this.router.navigate(['admin-panel/products']);
}
和:
public addNewProduct() {
if (this.f.valid) {
this.product.count = 1;
this.productService.saveProduct(this.product).subscribe(data => console.log('product added or updated'));
}
this.router.navigate(['admin-panel/products']);
}
当我使用第一种方法时,重定向到admin-panel / products后,模板的视图会正确更新。当我使用第二种方法时,需要手动刷新页面才能显示带有添加项的更新视图。
为什么这些括号会有所不同?拜托,开导我!
答案 0 :(得分:1)
(data) => {}
与data => {}
基本相同。
如果元组中只有一个值,则可能会丢失括号。
如果subscribe回调提供具有两个值的元组,则将有所不同。然后,您需要括号。 (data, moreData) => {}
。
您的问题不在此代码中。
您遇到了时间问题,因为根据saveProduct()
的执行时间,对this.router.navigate(['admin-panel/products']);
的调用可能执行得太早了。更改代码,以便在执行您的订阅回调时执行导航。
public addNewProduct() {
if (this.f.valid) {
this.product.count = 1;
this.productService.saveProduct(this.product).subscribe(data => {
console.log('product added or updated'));
// Place it here.
this.router.navigate(['admin-panel/products']);
});
// Because here is too early.
}
else {
// And here if your condition is not met, if this seems logical to you.
this.router.navigate(['admin-panel/products']);
}
}
证明执行计时问题的测试:
public test() {
of('').pipe(delay(1000)).subscribe(() => console.log(1));
console.log(2);
}
Output:
2
1