
angular signals 代表了 angular 应用程序中状态管理和反应性的革命性方法。这份综合指南将引导您了解有关信号所需了解的所有内容,从基本概念到高级实现。
信号是 angular 16+ 中引入的新原语,它提供了一种处理反应式状态管理的方法。它们是值的特殊包装,当这些值发生变化时通知感兴趣的消费者。
import { signal } from '@angular/core';
// creating a simple signal
const count = signal(0);
// reading signal value
console.log(count()); // output: 0
// updating signal value
count.set(1);
import { component, signal } from '@angular/core';
@component({
selector: 'app-counter',
template: `
<div>
<p>count: {{ count() }}</p>
<button (click)="increment()">increment</button>
</div>
`
})
export class countercomponent {
count = signal(0);
increment() {
this.count.set(this.count() + 1);
}
}
const name = signal('john');
name.set('jane');
const counter = signal(0); counter.update(value => value + 1);
const user = signal({ name: 'john', age: 25 });
user.mutate(value => {
value.age = 26;
});
计算信号自动从其他信号中获取其值:
import { signal, computed } from '@angular/core';
const price = signal(100);
const quantity = signal(2);
const total = computed(() => price() * quantity());
console.log(total()); // output: 200
效果允许您在信号变化时执行副作用:
import { signal, effect } from '@angular/core';
const message = signal('hello');
effect(() => {
console.log(`message changed to: ${message()}`);
});
message.set('hi'); // logs: "message changed to: hi"
interface product {
id: number;
name: string;
price: number;
}
@component({
selector: 'app-shopping-cart',
template: `
<div>
<h2>shopping cart</h2>
<div *ngfor="let item of cartitems()">
{{ item.name }} - ${{ item.price }}
</div>
<p>total: ${{ carttotal() }}</p>
</div>
`
})
export class shoppingcartcomponent {
cartitems = signal<product[]>([]);
carttotal = computed(() =>
this.cartitems().reduce((total, item) => total + item.price, 0)
);
addtocart(product: product) {
this.cartitems.update(items => [...items, product]);
}
removefromcart(productid: number) {
this.cartitems.update(items =>
items.filter(item => item.id !== productid)
);
}
}
@component({
selector: 'app-user-form',
template: `
<form (submit)="handlesubmit($event)">
<input
[value]="formdata().name"
(input)="updatename($event)"
placeholder="name"
>
<input
[value]="formdata().email"
(input)="updateemail($event)"
placeholder="email"
>
<button type="submit">submit</button>
</form>
`
})
export class userformcomponent {
formdata = signal({
name: '',
email: ''
});
updatename(event: event) {
const input = event.target as htmlinputelement;
this.formdata.update(data => ({
...data,
name: input.value
}));
}
updateemail(event: event) {
const input = event.target as htmlinputelement;
this.formdata.update(data => ({
...data,
email: input.value
}));
}
handlesubmit(event: event) {
event.preventdefault();
console.log('form submitted:', this.formdata());
}
}
// good practice
const userprofile = signal<userprofile | null>(null);
// better practice with type safety
interface userprofile {
name: string;
email: string;
}
const userprofile = signal<userprofile>({
name: '',
email: ''
});
性能优化
错误处理
const apidata = signal<string | null>(null);
const error = signal<error | null>(null);
async function fetchdata() {
try {
const response = await fetch('api/data');
const data = await response.json();
apidata.set(data);
error.set(null);
} catch (e) {
error.set(e as error);
}
}
function createdebouncedsignal(initialvalue: string, delay: number) {
const value = signal(initialvalue);
let timeout: any;
return {
get: value,
set: (newvalue: string) => {
cleartimeout(timeout);
timeout = settimeout(() => {
value.set(newvalue);
}, delay);
}
};
}
// usage
const searchquery = createdebouncedsignal('', 300);
@Component({
template: `
<div>
<div *ngIf="loading()">Loading...</div>
<div *ngIf="error()">{{ error() }}</div>
<div *ngIf="data()">
{{ data() | json }}
</div>
</div>
`
})
export class AsyncDataComponent {
data = signal<any>(null);
loading = signal(false);
error = signal<string | null>(null);
async fetchData() {
this.loading.set(true);
try {
const response = await fetch('api/data');
const result = await response.json();
this.data.set(result);
} catch (e) {
this.error.set(e.message);
} finally {
this.loading.set(false);
}
}
}
问:signals 和behaviorsubject 有什么区别?
答:信号更简单、性能更高,并且直接集成到 angular 的变化检测中。 behavioursubjects 是需要手动订阅管理的 rxjs 可观察对象。
问:我可以将 signals 与 ngrx 一起使用吗?
答:是的,signals 可以补充 ngrx 的本地组件状态,而 ngrx 则处理全局应用程序状态。
问:信号会取代传统的属性绑定吗?
答:不,信号是一种附加工具。当您需要反应式状态管理时可以使用它们,但传统的属性绑定对于更简单的情况仍然有效。
问:signals 在较旧的 angular 版本中可用吗?
答:信号是在 angular 16 中引入的。对于旧版本,您需要使用 rxjs observables 等替代方案。
angular signals 提供了一种强大而有效的方法来处理应用程序中的反应式状态管理。通过遵循本指南中概述的示例和最佳实践,您将能够在自己的项目中实现信号。请记住从简单开始,随着您的需求增长逐渐融入更高级的模式。
掌握信号的关键是练习和理解它们的反应性质。从实现基本示例开始,然后当您熟悉这些概念后,再逐步实现更复杂的场景。
以上就是从基础到高级:逐步掌握角度信号的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号