# 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[​](#register-an-element-manually "Direct link to 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 latest [`ForesightElementState`](/docs/angular/configuration/registration-options.md#state-fields)
* `update(options)`: updates the existing registration, resetting omitted fields to their defaults
* `unregister()`: removes the element from the manager
* `getSnapshot()`: reads the current state snapshot

## Update options[​](#update-options "Direct link to Update options")

Pass the full configuration you want to keep. For example, this update removes the initial `hitSlop: 40` and restores the current global `defaultHitSlop`:

```
this.registration?.update({

  callback: () => void fetch("/api/checkout"),

  name: "checkout-button",

  enabled: this.canPrefetch(),

})
```

## Listen to manager events[​](#listen-to-manager-events "Direct link to 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`](/docs/angular/injectForesightEvent.md) usually gives cleaner cleanup.
