Property 'mutate' does not exist on type 'WritableSignal<Vehicle>'.
这是我的代码片段:
import { Component, signal, computed, effect } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
export interface Vehicle {
id: number;
name: string;
price: number;
}
@Component({
selector: 'app-root',
imports: [FormsModule],
template: `
<h1>{{ quantity() }}</h1>
<select [ngModel]="quantity()" (change)="onSelectQ($event)">
<option *ngFor="let x of quantityArr()">{{ x }}</option>
</select>
<div>Vehicle: {{ selectedVehicle().name }}</div>
<div>Vehicle Price: {{ selectedVehicle().price }}</div>
<div>Total: {{ exPrice() }}</div>
`,
})
export class App {
quantity = signal<number>(1);
quantityArr = signal<number[]>([1, 2, 3, 4, 5, 6, 7, 8, 9]);
vehicles = signal<Vehicle[]>([
{ id: 1, name: 'Lexus', price: 100 },
{ id: 2, name: 'Zen', price: 200 },
{ id: 3, name: 'Duster', price: 300 },
]);
selectedVehicle = signal<Vehicle>(this.vehicles()[0]);
exPrice = computed(() => this.selectedVehicle().price * this.quantity());
constructor() {
// Trying to use mutate here:
this.selectedVehicle.mutate((v: Vehicle) => (v.price = v.price * 1.2));
}
quantityEffect = effect(() => {
console.log(this.quantity());
});
onSelectQ(event: any) {
this.quantity.set(Number(event.target.value));
}
}
bootstrapApplication(App);
package.json
{
"dependencies": {
"@angular/core": "^19.0.0",
"@angular/forms": "^19.0.0",
"@angular/platform-browser": "^19.0.0",
"rxjs": "^7.8.1",
"zone.js": "~0.15.0"
},
"devDependencies": {
"@angular/cli": "^19.0.0",
"@angular/compiler-cli": "^19.0.0",
"typescript": "^5.6.3"
}
}
为什么 Angular 19 的 mutate 方法不适用于 WritableSignal?在 Angular 中更新信号对象属性的正确方法是什么?
我正在学习版本 19 的角度信号,我正在关注下面的视频
https://www.youtube.com/watch?v=oqYQG7QMdzw&list=PLErOmyzRKOCr07Kcnx75Aqh6PWSbIokPB&index=1
mutate
方法已在v18中删除,因此此后不再可用。该视频有点过时了。
如果你想改变信号,你要么依赖
set
或
update
方法。