Astro-DX Logo Astro-DX
GitHub
@astro-dx/core · Services

Services

Singleton classes with register/inject. Share reactive state across any island with explicit dependencies.

The two cards below are completely independent Astro islands. Component A mutates the service, Component B receives derived state from the same instance.
Component A — manages service state
0
Component B — receives from service
Double: 0

Code — manager component

"code-keyword">import { inject } "code-keyword">from '@astro-dx/core';
"code-keyword">import { getElement } "code-keyword">from '@astro-dx/dom';
"code-keyword">import { onClick } "code-keyword">from '@astro-dx/events';
"code-keyword">import { CounterServiceClass } "code-keyword">from '../../services/counter.service';

"code-keyword">const counter = "code-function">inject(CounterServiceClass);

"code-function">getElement('#count-value')."code-function">text(counter.count);

"code-function">onClick('#btn-inc', () => counter."code-function">increment());
"code-function">onClick('#btn-dec', () => counter."code-function">decrement());
"code-function">onClick('#btn-reset', () => counter."code-function">reset());

Code — receiver component

"code-keyword">import { inject } "code-keyword">from '@astro-dx/core';
"code-keyword">import { getElement } "code-keyword">from '@astro-dx/dom';
"code-keyword">import { CounterServiceClass } "code-keyword">from '../../services/counter.service';

"code-keyword">const counter = "code-function">inject(CounterServiceClass);

"code-function">getElement('#double-value')."code-function">text(counter.double);

Cross-island list with shared service

This pair of islands also shares one service instance via inject().

Island A — Add to cart
Keyboard Mouse Monitor Headphones
Island B — Cart summary
Total items 0
    Clear cart

    Code example

    "code-keyword">import { register } "code-keyword">from '@astro-dx/core';
    "code-keyword">import { CounterServiceClass } "code-keyword">from '../../services/counter.service';
    "code-keyword">import { ShopServiceClass } "code-keyword">from '../../services/shop.service';
    
    "code-function">register([CounterServiceClass, ShopServiceClass]);
    
    "code-keyword">import { inject } "code-keyword">from '@astro-dx/core';
    
    "code-keyword">const cart = "code-function">inject(ShopServiceClass);
    cart."code-function">addToCart({ id: 'k-1', name: 'Keyboard', price: 99 });

    Playground

    Two independent islands sharing reactive state. Edit the code and hit Run.