0Pricing
Angular Academy · 课时

使用 computed 派生状态

从基础状态构建读取模型

使用 computed 派生状态 是 CoddyKit 上的免费 Angular Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Angular Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Angular Academy 课程共包含 4 节课。

派生状态

状态通常是从其他状态计算得出的:例如由商品得到总额、得到筛选后的列表,或得到有效性标志。Angular 的 computed() 会创建一个只读信号,其值派生自其他信号。

创建 computed

向 computed() 传入一个函数。该函数读取其他信号并返回一个值。只有当某个依赖发生变化时,结果才会重新计算。

import { signal, computed } from '@angular/core';

const price = signal(10);
const qty = signal(3);
const total = computed(() => price() * qty());
// total() === 30

自动跟踪依赖

您无需声明依赖。只要是在函数中读取的信号,都会自动成为依赖。更改 qty 会重新计算 total;更改无关信号则不会。

记忆化

computed() 会缓存结果。反复读取时,在依赖发生变化之前只会运行一次函数。即使模板中有许多绑定,也能以较低成本访问派生的读取模型。

const expensive = computed(() => heavyTransform(data()));
// reading expensive() repeatedly does not re-run heavyTransform

存储中的 computed

在信号存储中,公开派生的读取模型,让组件直接使用可渲染的值,而不必在模板中重新计算。

@Injectable({ providedIn: 'root' })
export class CartStore {
  private _items = signal<Item[]>([]);
  readonly items = this._items.asReadonly();
  readonly count = computed(() => this._items().length);
  readonly subtotal = computed(() =>
    this._items().reduce((s, i) => s + i.price, 0));
}

链接 computed

计算信号可以读取其他计算信号。您可以构建分层的读取模型:基础派生结果为更高层的读取模型提供数据。

const subtotal = computed(() => items().reduce((s, i) => s + i.price, 0));
const tax = computed(() => subtotal() * 0.2);
const total = computed(() => subtotal() + tax());

筛选与搜索

一种常见的读取模型是:根据搜索信号筛选列表。每当列表或 query 发生变化时,筛选结果都会更新。

const query = signal('');
const all = signal<User[]>([]);
const filtered = computed(() =>
  all().filter(u => u.name.toLowerCase().includes(query().toLowerCase())));

无副作用

computed() 函数必须是纯函数:只能读取信号并返回值。不要在其中修改状态、调用 API 或写入其他信号。需要执行副作用时,请改用 effect()。

相等性与跳过更新

默认情况下,computed 使用引用相等性(Object.is)来判断值是否发生变化。如果新值与旧值相等,就不会通知使用者,从而避免不必要的工作。

const status = computed(() => count() > 0 ? 'has' : 'empty');
// while count stays > 0 the string stays 'has' -> no downstream updates

在模板中使用 computed

在模板中读取计算信号的方式与读取普通信号相同。Angular 只会更新计算值确实发生变化的绑定。

@Component({
  template: '<p>Items: {{ store.count() }} — Total: {{ store.subtotal() }}</p>'
})
export class SummaryComponent {
  store = inject(CartStore);
}

computed 与方法

对于应自动更新并进行记忆化的派生状态值,请使用 computed()。对于带参数的一次性计算,或应按需执行的计算,请使用普通方法。

快速检查

检查您对计算信号的理解。

回顾

您使用 computed() 构建了派生状态:自动跟踪依赖、记忆化纯函数、可链接的读取模型,以及通过相等性跳过更新。请从存储中公开计算得到的读取模型,让模板保持声明式。

常见问题解答

「使用 computed 派生状态」课时是免费的吗?

是的 — 「使用 computed 派生状态」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Angular Academy 课程的其余内容,请升级到 CoddyKit PRO。 Angular Academy 课程共包含 4 节课。

「使用 computed 派生状态」这节课中我会学到什么?

从基础状态构建读取模型 你通过在浏览器中直接运行的动手代码来练习 Angular Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Angular Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Angular Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「使用 computed 派生状态」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Angular Academy 课中编写并运行代码吗?

能。每节 Angular Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 服务中的 SignalStore
  2. 使用 computed 派生状态
  3. 以不可变方式更新状态
  4. 连接信号与 RxJS
← 返回 Angular Academy