The class below declares a signal and an update function for the signal:
export class ProductSidebarService {
public productSidebarSignal = signal<{
productSidebarData: ProductSidebarData;
}>({ productSidebarData: new ProductSidebarData() });
public updateSidebarData = (productSidebarData: ProductSidebarData) => {
this.productSidebarSignal.set({productSidebarData:{... productSidebarData} });
console.dir('ProductSidebarService.productSidebarSignal', this.productSidebarSignal())
};
}
The class below declares an effect that is supposed to fire when the above signal is updated but the effect never fires:
export class ProductGalleryComponent {
private productSidebarService = inject(ProductSidebarService);
public productSidebarData = this.productSidebarService.productSidebarSignal();
private productSidebarEffect = effect(() => {
console.dir('ProductGalleryComponent.productSidebarSignal', this.productSidebarService.productSidebarSignal())
});
}
The problem might be console.dir
, which does not show the output of the signal when passed in with comma separated values, apart from that from the data provided, the effect is firing.
Also make sure, you have console.log
set on when you update the signal and when you initialize the effect, you can set a console.log
on the constructor
of ProductGalleryComponent
if the component is initialized after the signal is set, the effect might fire only once.
Also note, that signal updates are kind of debounced, so it will fire only once.
import { Component, inject, Injectable, signal, effect } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import {
HttpClient,
HttpParams,
provideHttpClient,
} from '@angular/common/http';
import { Observable, map } from 'rxjs';
export class ProductSidebarData {
constructor(public test: string = '') {}
}
@Injectable({ providedIn: 'root' })
export class SomeService {
public productSidebarSignal = signal<{
productSidebarData: ProductSidebarData;
}>({ productSidebarData: new ProductSidebarData() });
public updateSidebarData = (productSidebarData: ProductSidebarData) => {
this.productSidebarSignal.set({
productSidebarData: { ...productSidebarData },
});
console.log(
'ProductSidebarService.productSidebarSignal',
this.productSidebarSignal()
);
};
}
@Component({
selector: 'app-root',
template: `asdf`,
})
export class App {
productSidebarService = inject(SomeService);
private productSidebarEffect = effect(() => {
console.log(
'ProductGalleryComponent.productSidebarSignal',
this.productSidebarService.productSidebarSignal()
);
});
constructor() {
console.log('test');
}
ngOnInit() {
console.log('storing');
this.productSidebarService.updateSidebarData(
new ProductSidebarData('qwerty')
);
this.productSidebarService.updateSidebarData(
new ProductSidebarData('qwerty1')
);
}
}
bootstrapApplication(App, {
providers: [provideHttpClient()],
});