角度信号 - 有什么优势?

问题描述 投票:0回答:0

我想了解使用 Angular Singnals 的优势。许多解释中都给出了一个计数示例,但我想了解的是,以这种方式使用信号的优势与我在下面通过变量 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 signals angular-signals
© www.soinside.com 2019 - 2024. All rights reserved.