ForesightService
ForesightService is the injectable Angular API underneath the directive and component. Use it when a directive is not a good fit, or when you want to register an element from lifecycle code.
Register an element manually
import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild, inject } from "@angular/core"
import { ForesightService, type ForesightRegistration } from "@foresightjs/angular"
@Component({
selector: "app-manual-prefetch",
standalone: true,
template: `<button #button>Checkout</button>`,
})
export class ManualPrefetchComponent implements AfterViewInit, OnDestroy {
@ViewChild("button", { static: true }) button!: ElementRef<HTMLButtonElement>
private readonly foresight = inject(ForesightService)
private registration: ForesightRegistration | null = null
ngAfterViewInit(): void {
this.registration = this.foresight.register(this.button.nativeElement, {
callback: () => void fetch("/api/checkout"),
name: "checkout-button",
hitSlop: 40,
})
}
ngOnDestroy(): void {
this.registration?.unregister()
}
}
register() returns a ForesightRegistration:
state: an Angular signal with the latestForesightElementStateupdate(options): patches the existing registrationunregister(): removes the element from the managergetSnapshot(): reads the current state snapshot
Update options
this.registration?.update({
callback: () => void fetch("/api/checkout"),
name: "checkout-button",
enabled: this.canPrefetch(),
})
Listen to manager events
Use listen() for app-level analytics or debugging outside a component injection context:
const stopListening = this.foresight.listen("callbackInvoked", event => {
console.log("Prefetch started", event.state.name)
})
stopListening()
Inside a component, injectForesightEvent usually gives cleaner cleanup.