考虑到下面的Angular Signals个示例,我有点困惑,当数组API(如forEach)足以触发react 性并更新UI/模板时,我何时应该使用信号API(如mutate()和update())?这里有什么不同?使用的Angular 版本:16.0.1
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule],
template: `
{{usersList() | json}}
`,
})
export class App {
usersList: Signal<any> = inject(UserService).getUsersList();
constructor() {
}
}
bootstrapApplication(App);
@Injectable({
providedIn: 'root',
})
export class UserService {
private users = signal([
{ id: 1, name: 'Peter', country: 'USA' },
{ id: 2, name: 'Party Boy', country: 'USA' },
{ id: 3, name: 'John Connor', country: 'USA' },
]);
constructor() {
window.setTimeout(()=>{
this.changeUsersListWithoutMutate();
}, 3000),
window.setTimeout(()=>{
this.changeUsersListWithMutate();
}, 5000)
}
changeUsersListWithoutMutate(){
this.users().forEach((item) => {
if (item.id === 1) {
item.name = "changeListWithoutMutate";
}
});
}
changeUsersListWithMutate(){
this.users.mutate((data) => {
data.forEach((item) => {
if (item.id === 1) {
item.name = "changeListWithMutate";
}
});
});
}
getUsersList() {
return this.users;
}
}