Why does my effect gets looped when i don't call the signal in it?

Discussão em 'Angular' iniciado por Lenard, Março 20, 2025.

  1. Lenard

    Lenard Guest

    export class Service {
    private http = inject(HttpClient)
    private injector = inject(Injector); // Hier wird der Injector geholt

    objectId = signal<string | null>(null);

    private _object = signal<IObject | null>(null);
    object = computed(() => this._object()); // Read-Only access

    // Fehler-Signal, falls die API fehlschlägt
    error = signal<string | null>(null);

    constructor() {
    effect(() => {
    const objectId = this.objectId()
    // this._object.set(null)
    this.error.set(null)

    if (objectId) {
    const secondId = 'secondId'
    console.log('id', objectId)
    this.getObjectById(objectId, secondId)
    return;
    }
    }, { allowSignalWrites: true })
    }

    setObjectId(id: string | null) {
    this.objectId.set(id);
    }

    private getObjectById(objectId: string, secondId: string) {
    this.http.get<IObject>(this.objectUrl + `GetObjectById/${objectId}/${secondId}`).subscribe({
    next: (object) => {

    this._object.set(object)
    },
    error: () => {
    console.log('error')
    },
    })
    console.log(this.object())
    // untracked(() => console.log(this.object()))
    }
    }


    i have this call (and yes it works i replaced the real names and the ids) and when i have this console.log(this.object()) after my subscribe or even before I will get a loop. If i put the log in the subscribe i won't get a loop and with untracked i won't get a loop too. Is this really as it works because nothing in this effect should trigger the call again and again, my first solution was to comment out this._object.set(null) but not even this triggers the loop

    Continue reading...

Compartilhe esta Página