Data fetching for Angular 14+
Create a service that fetches data
constendpoint="https://jsonplaceholder.typicode.com/todos"
@Injectable({providedIn: "root"})exportclassFetcherimplementsFetchable<Todo[]>{privatehttp=inject(HttpClient)fetch(userId: string){returnthis.http.get(endpoint,{params: { userId }})}}Create a resource
import{createResource,revalidateOnFocus,refreshInterval,revalidateOnReconnect}from"@mmuscat/angular-swr"exportconstTODOS=createResource(Fetcher,{features: [revalidateOnFocus,revalidateOnReconnect,refreshInterval(60_000)]})Provide and use resource in component
import{TODOS}from"./resource"
@Component({selector: "app-todos",templateUrl: "./todos.component.html",providers: [TODOS],})exportclassTodosComponent{protectedtodos=inject(TODOS)
@Input()userId: stringngOnChanges(){this.todos.fetch(this.userId)}}Read values in template
<!-- todos.component.html --><div*ngIf="todos.error">
Something went wrong
<button(click)="todos.revalidate()">Retry</button></div><spinner*ngIf="todos.pending"></spinner><todo*ngFor="let todo of todos.value" [value]="todo"></todo>exportinterfaceResourceOptions{providedIn?: Type<any>|"root"|"platform"|"any"|nullimmutable?: booleantimeoutMs?: numberdedupeMs?: numbercache?: booleanrefetchIfStale?: booleanserialize?: (...params: any[])=>stringfeatures?: ResourceFeatureWithOptions<{}>[]}| property | default | description |
|---|---|---|
| providedIn | null | Configure which module the resource is provided in |
| immutable | false | Prevent refetching a resource that is already cached with the given params |
| timeoutMs | 3000 | How long a resource should wait after fetching without receiving a response before it is marked as slow |
| dedupeMs | 2000 | How long a resource should wait before allowing a duplicate fetch with the same params |
| cache | true | Disables caching when set to false, useful when fetch is used to send data |
| revalidateIfStale | true | Control whether a resource should revalidate when mounted if there is stale data |
| serialize | JSON.stringify | Serializer used to stringify fetch parameters |
| features | void | A list of ResourceFeatureWithOptions that add additional behaviours to the resource |
Resource behavior can be customised by adding features.
Revalidate a resource every time the current page receives window focus.
Revalidate a resource every time the network connection comes back online.
Revalidate a resource periodically according to a timer.
Create a class that implements the ResourceFeature interface.
interfaceResourceFeature<Textends{}>{onInit?(resource: Resource,options: T): voidonConnect?(resource: Resource,options: T): voidonDisconnect?(resource: Resource,options: T): voidonDestroy?(resource: Resource,options: T): void}Example
import{createFeature,Fetchable,Resource,ResourceFeature}from"@mmuscat/angular-swr"interfaceLoggerOptions{token?: Type<{log: (resource: Resource)=>void}>}
@Injectable({providedIn: "root"})exportclassLoggerimplementsResourceFeature<LoggerOptions>{privateinjector=inject(INJECTOR)onInit(resource: Resource<T>,{ token }: LoggerOptions){constlogger=this.injector.get(token,console)resource.subscribe(()=>{logger.log(resource)})}}exportfunctionlogger(token: Type<any>){returncreateFeature(Logger,{ token })}Usage
@Injectable({providedIn: "root"})classMyLogger{log(resource: Resource){// log implementation}}constRESOURCE=createResource(Fetcher,{features: [logger(MyLogger)]})