打字稿的订阅方法中 'data' 和 '(data)' 有什么区别?
What is the difference between 'data' and '(data)' in typescript's subscribe method?
如标题所说。有什么区别:
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 后正确更新。当我使用第二种方法时,需要刷新手动页面以显示带有添加项的更新视图。
为什么这些括号会有所不同?请赐教!
(data) => {}
在这里与 data => {}
基本相同。
如果元组中只有一个值,则可以省略括号。
如果订阅回调提供具有两个值的元组,情况会有所不同。然后你需要括号。 (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
如标题所说。有什么区别:
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 后正确更新。当我使用第二种方法时,需要刷新手动页面以显示带有添加项的更新视图。
为什么这些括号会有所不同?请赐教!
(data) => {}
在这里与 data => {}
基本相同。
如果元组中只有一个值,则可以省略括号。
如果订阅回调提供具有两个值的元组,情况会有所不同。然后你需要括号。 (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