gpt4 book ai didi

Angular 信号 - 有什么优势?

转载 作者:行者123 更新时间:2023-12-03 07:57:41 33 4
gpt4 key购买 nike

我试图了解使用 Angular Signals 的优势。许多解释中都给出了计数示例,但我试图理解的是,与我下面通过变量 myCount 和 myCountDouble 所做的方式相比,以这种方式使用信号的优点?

https://stackblitz.com/edit/angular-qtd3ku?file=src/main.ts

这是我的代码+ stackblitz

import 'zone.js/dist/zone';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { signal } from './signals/signal';
import { computed } from './signals/computed';
import { effect } from './signals/effect';
import { TestArraysCmp } from './testing-arrays.component';
import { TestObjectsCmp } from './testing-objects.component';

/*
⚠️ Please keep in mind that this is only the signals implementation. We still depend on zone and current CD strategy to propagate change in the template which might not be the case when Angular releases signals officially!
*/

// Signals are primitives, so we can use them outside the component class
const myValue = signal(10000);

effect(() => {
console.log('MyValue changed', myValue());
});

// Uncomment this
// setInterval(() => {
// myValue.update((s) => s - 1);
// }, 1000);

@Component({
selector: 'my-app',
standalone: true,
template: `
<div>Count: {{ count() }}</div>
<div>Double: {{ double() }}</div>
<div>MyCount: {{myCount}}</div>
<div>MyDoubleCount: {{myCountDouble}}</div>
<button (click)="inc()">Increase</button>
<button (click)="reset()">Reset</button>

<br>
<!-- <test-arrays /> -->
<!-- <test-objects /> -->

`,
imports: [TestArraysCmp, TestObjectsCmp],
})
export class App {
myCount: number = 0;
myCountDouble: number = 0;
myCountType: string;

count = signal(0);

double = computed(() => this.count() * 2);

countType = computed(() => (this.count() % 2 === 0 ? 'even' : 'odd'));

constructor() {
effect(() => {
console.log('Count changed', this.count());
console.log(this.count(), 'is', this.countType());
});
}

inc() {
this.count.update((c) => c + 1);
this.myCount = this.myCount + 1;
this.myCountDouble = this.myCount * 2;
this.myCountType = this.myCount % 2 === 0 ? 'even' : 'odd';
console.log('Old Way', this.myCount, 'is', this.myCountType);
}
reset() {
this.count.set(0);
this.myCount = 0;
this.myCountDouble = 0;
this.myCountType = '';
}
}

bootstrapApplication(App);

最佳答案

优势主要与 Angular 处理变化检测的方式有关。

使用 Zone.js,当您触发 inc() 方法时,Angular 将查找整个组件树以查找更改,即使只有一件事发生了更改。

通过信号,我们具体表明只有特定的事情发生了变化并且需要更新。

由于更新计数器是一个同步操作 - 我们不需要等待 API 响应,我们知道该值,因此我们可以使用它立即更新计数器 - 使用信号会执行得更好,因为它准确地向 Angular 指示,仅应更新依赖于该信号的元素,从而消除了对整个组件树进行脏检查的需要。

关于 Angular 信号 - 有什么优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75646567/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com