Binding Angular route params to computed signals

Discussão em 'Angular' iniciado por Jens R., Novembro 10, 2024.

  1. Jens R.

    Jens R. Guest

    I'm trying to make my code as reactive as possible, switching from explicit route subscription to withcomponentinputbinding.

    export class CustomerProfileComponent {
    private readonly oms = inject(OMSService);
    private readonly route = inject(ActivatedRoute);

    id = input<number>();

    // this works but isn't using the mapped input signal
    customer = toSignal(
    this.route.params.pipe(
    switchMap((params) => this.oms.getCustomer(Number(params['id'])))
    )
    );

    // this doesn't work because getCustomer returns an Observable.
    // Adding toSignal() doesn't work either, due to the context, but
    // looking for something like this!
    xcustomer = computed(() => this.oms.getCustomer(this.id()));

    }


    If I call using route http://localhost:4200/#/customers/12 it will show the output from {{ id() }} as 12 as described by the mapped route, so I know that's working. But the xcustomer computed value doesn't get resolved and is output as:

    { "source": { "source": { "source": {} } } }

    The service call signature is:

    getCustomer(id?: number): Observable<Customer>


    Is there a way to use the InputSignal that is bound from the route as a computed source in this way? Using Angular 18.2.11.

    Continue reading...

Compartilhe esta Página