這似乎是一個非常愚蠢的問題,但我在這里。我能夠獲取我的產品、呈現表單并正確填充值。
而不是有兩種方法create,update我只想擁有save. 我正在嘗試根據product$可觀察到的結果來弄清楚我是在使用現有產品還是在創建新產品。
// product.component.ts
public product$ = this.productService.product$;
ngOnInit(): void {
this.product$.pipe(tap((product) => console.log('product', product))).subscribe((product) => {
this.form = new FormGroup({
name: new FormControl(product?.name, [
Validators.required,
]),
description: new FormControl(product?.description, [
Validators.required,
]),
});
});
}
...
// this is the goal
save(form: FormGroup): void {
if (form.invalid) {
return;
}
if(product$) {
this.productService.update(...);
} else {
this.productService.create(...);
}
}
我知道我可以(再次)訂閱,product$但我覺得我已經獲得了我需要的價值?
- 創建產品時,我的網址看起來像
example.com/products - 更新時,網址將始終為
example.com/products/123
所以我想我可以做類似的事情:
if (this.activatedRoute.params.pipe(tap((route) => console.log(route)))) {
console.log('existing');
} else {
console.log('new');
}
我知道我無法進入pipe查看我所擁有的東西,所以我不確定該嘗試什么——但我覺得我擁有這么簡單的事情所需的所有資訊。我怎樣才能檢查productIdor 東西所以我只需要一個save方法?
uj5u.com熱心網友回復:
使 productId 成為隱藏的表單控制元件,以便在保存時可以查看表單控制元件的值。從 observable 創建表單是個壞主意,因為您將在每次產品更新時創建一個新表單,這可能不是您想要的。
表單創建看起來像這樣。
this.form = new FormGroup({
name: new FormControl(product?.name, [
Validators.required,
]),
description: new FormControl(product?.description, [
Validators.required,
]),
productId: new FormControl(product?.productId, []),
});
保存看起來像這樣
save(form: FormGroup): void {
if (form.invalid) {
return;
}
if(form.controls['productId'].value !== null) {
this.productService.update(...);
} else {
this.productService.create(...);
}
}
uj5u.com熱心網友回復:
不要在 if 陳述句中使用 observable。這不是一個值。相反,如果邏輯應該進入訂閱內部。訂閱而不是點擊。Tap 用于除錯和中間流的副作用。根據經驗,您希望將副作用降至最低。
this.activatedRoute.params.pipe(take(1)).subscribe((route) => {
// get the id from route
if (id) {
console.log('existing');
} else {
console.log('new');
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/529090.html
標籤:有角度的角反应形式
上一篇:外殼:未能將錯誤流代碼保存到檔案
