Why do I need AbortSignal when using the resource API of angular. What is it's use?

Discussão em 'Angular' iniciado por Naren Murali, Fevereiro 24, 2025.

  1. Naren Murali

    Naren Murali Guest

    I have been defining resource as follows:

    resource: ResourceRef<any> = resource<ResourceRequest | undefined, any>({
    request: (): ResourceRequest | undefined => {
    return {
    id: this.id(),
    };
    },
    loader: ({ request: { id }, abortSignal }) => {
    return fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then(
    (res: any) => res.json()
    );
    },
    });


    Seems sufficient to achieve what I want, but I see this pattern in blogs and youtube where they add the AbortSignal to the fetch request.

    loader: ({ request: { id }, abortSignal }) => {
    return fetch(`https://jsonplaceholder.typicode.com/todos/${id}`, {
    signal: abortSignal,
    }).then((res: any) => res.json());
    },


    What is the necessity for this?

    Below is my minimal reproducible code with working stackblitz.

    TS:


    id = signal(1);
    rs = ResourceStatus;
    http = inject(HttpClient);
    resourceControl = signal(true);
    resource: ResourceRef<any> = resource<ResourceRequest | undefined, any>({
    request: (): ResourceRequest | undefined => {
    return {
    id: this.id(),
    };
    },
    loader: ({ request: { id }, abortSignal }) => {
    return fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then(
    (res: any) => res.json()
    );
    },
    });

    HTML:


    <div>
    <div>
    Resource Request triggers:
    </div>
    <div>
    <input [(ngModel)]="id" type="number"/>
    </div>
    </div>
    <div>
    @if(![rs.Loading, rs.Reloading].includes(resource.status())) {
    {{resource.value() | json}}
    } @else{
    Loading...
    }
    </div>

    Stackblitz Demo

    Continue reading...

Compartilhe esta Página