Updating Signal Values in Angular's ngAfterViewInit: Troubleshooting Stale Effect Values

Discussão em 'Angular' iniciado por Reginna, Outubro 28, 2024.

  1. Reginna

    Reginna Guest

    I am trying to update a signal value in ngAfterViewInit, but the effect always receives the old value.

    Here is my code:

    export class examplePageComponent implements AfterViewInit {
    syncDirect = signal<{ init: boolean; sync: boolean }>({ init: false, sync: false });

    constructor() {
    effect(
    () => {
    // Always show: {init: false, sync: false}
    console.log('syncDirect', this.syncDirect());

    if (!this.syncDirect().init && this.syncDirect().sync) {
    // Not run into here
    console.log('????????');
    this.syncDirect.update((v) => ({ ...v, init: true }));
    this.onSync();
    }

    //... other thing
    },
    { allowSignalWrites: true }
    );
    }

    ngAfterViewInit(): void {
    this.#router.events.pipe(filter((event) => event instanceof NavigationEnd)).subscribe(() => {
    const navigation = this.#router.getCurrentNavigation();
    if (navigation?.extras.state) {
    const stateSync = navigation.extras.state['sync'];
    if (stateSync) {
    console.log('stateSync'); // it's working
    this.syncDirect.update((v) => ({ ...v, sync: true }));
    console.log(this.syncDirect()); // show: {init: false, sync: true}
    }
    }
    });
    }
    }


    Am I doing something wrong? How can I fix it?

    Continue reading...

Compartilhe esta Página