How can I bind an id from the URL to an Angular signal and use that signal to fetch product...

Discussão em 'Angular' iniciado por zerotohero, Maio 2, 2025.

  1. zerotohero

    zerotohero Guest

    Goal I'm using Angular with the new signals feature and the experimental HttpResource. I want to:

    Extract an id parameter from the route. Bind this id to a signal. Use that signal to fetch product details from an API whenever the value changes.

    What I Tried


    export class ProductDetailComponent implements OnInit {
    private _route = inject(ActivatedRoute);

    readonly productId = computed(() => {
    return Number(this._route.snapshot.paramMap.get('productId'));
    });

    readonly productResource = computed(() => {
    const id = this.productId();

    if (!id) return null;

    return httpResource<any>({
    url: `product/${id}`,
    method: 'GET'
    });
    });

    readonly product = computed(() => this.productResource()?.value());
    }



    What I Expected


    Read the productId from the URL using Angular Router.
    Track it with a computed signal.
    Fetch product details automatically when the productId is available or changes.

    Continue reading...

Compartilhe esta Página