> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Share code with an Angular web app

Keep your stores and services in one library that both your Angular web app and your AngularLynx app import. Extend `@blotch/angular-lynx/tsconfig.shared.json` in that library, and TypeScript flags a browser-only API before it crashes on a phone.

## Set up the library

Give the shared library a `tsconfig.json` of its own that extends the preset:

```json title="libs/shared/tsconfig.json"
{
  "extends": "@blotch/angular-lynx/tsconfig.shared.json",
  "compilerOptions": {
    "strict": true,
    "noEmit": true,
    "module": "ES2022",
    "moduleResolution": "bundler"
  },
  "include": ["src/**/*.ts"]
}
```

Check it with `npx tsc -p libs/shared`, and add that command to CI or to your lint script.

- **Nothing else applies the preset.** `ng build`, `ng serve` and `ng test` compile the library's files with each app's own configuration, as before, so a browser-only API in the library only shows up when its own `tsc -p` runs. Without that step, the preset does nothing.
- **The preset sets `lib` and `types`.** They hold only what Lynx's [main thread](/guide/glossary.md#main-thread), where Angular runs, has. TypeScript's `dom` library isn't in them, so `document`, `window` and `localStorage` are type errors.
- **It needs `moduleResolution` set to `bundler`**, as above and as `ng new` sets it, so TypeScript finds the preset's types through the package's exports. `node16` works too, with `"module": "Node16"`, which it requires. `node` (node10) finds the preset's types, but not Angular's own entry points such as `@angular/common/http`, and TypeScript 6 reports it as deprecated unless you set `"ignoreDeprecations": "6.0"`. TypeScript 7 removes it.
- **The preset turns on `skipLibCheck`.** TypeScript then skips every declaration file, including the library's own `.d.ts` files, not just those in `node_modules`. Angular's declarations name DOM types the preset leaves out, so turning it off reports errors in them.
- **`@blotch/angular-lynx` must resolve from the library's folder.** In a workspace, the AngularLynx app's dependency is enough.

## Write a store

A store written against the preset runs in both apps:

```typescript title="libs/shared/src/todo-store.ts"
import { HttpClient, httpResource } from '@angular/common/http';
import {
  computed,
  inject,
  InjectionToken,
  Service,
  signal,
} from '@angular/core';

export type Todo = { id: string; title: string; done: boolean };

/** The server's address. Each app provides it. */
export const API_URL = new InjectionToken<string>('API_URL');

@Service()
export class TodoStore {
  readonly #http = inject(HttpClient);
  // One URL for reading and saving, with or without a slash at the end of
  // API_URL, and keeping any path it has (https://example.com/api).
  readonly #todosUrl = `${inject(API_URL).replace(/\/$/, '')}/todos`;
  readonly #query = signal('');

  readonly todos = httpResource<Todo[]>(() => {
    const url = new URL(this.#todosUrl);
    url.searchParams.set('q', this.#query());
    return url.href;
  });

  // A failed request leaves no value: reading value() then throws.
  readonly remaining = computed(() =>
    this.todos.hasValue()
      ? this.todos.value().filter((todo) => !todo.done).length
      : 0,
  );

  search(query: string): void {
    this.#query.set(query);
  }

  add(title: string) {
    const todo: Todo = { id: crypto.randomUUID(), title, done: false };
    return this.#http.post<Todo>(this.#todosUrl, todo);
  }
}
```

## Use HttpClient and httpResource

Each app adds `provideHttpClient()` to its own config. The library only injects `HttpClient` or calls `httpResource`, which work the same in both apps. See [HTTP requests](/guide/http.md).

**Give every request an absolute URL.** A Lynx app has no page URL to resolve `/api/todos` against. Provide the server's address from each app, as `API_URL` above:

```typescript title="src/app/app.config.ts"
import { provideHttpClient } from '@angular/common/http';
import { API_URL } from 'shared';

export const appConfig = {
  providers: [
    provideHttpClient(),
    { provide: API_URL, useValue: 'https://api.example.com' },
  ],
};
```

## What the library can use

Everything below works on the phone and in a current browser. Where Lynx's version does less, the preset's types do less too.

| API                                                                                    | On Lynx                                                                                                                                                                                                                                                                                                                        |
| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Angular: DI, signals, `resource`, `httpResource`, `HttpClient`, RxJS                   | As on the web                                                                                                                                                                                                                                                                                                                  |
| `console`                                                                              | `log`, `info`, `warn`, `error`, `debug`, `time`, `timeEnd`, `group`, `groupEnd`, `table` and `count`. No `trace`, `assert` or `dir`                                                                                                                                                                                            |
| `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`                           | Return numbers. Arguments after the delay aren't passed to the callback                                                                                                                                                                                                                                                        |
| `requestAnimationFrame`, `requestIdleCallback`, `queueMicrotask`                       | `requestIdleCallback` takes no options                                                                                                                                                                                                                                                                                         |
| `URL`, `URLSearchParams`                                                               | As on the web, with `URL.createObjectURL()` for a `Blob`                                                                                                                                                                                                                                                                       |
| `AbortController`, `AbortSignal`                                                       | No `AbortSignal.timeout()`, `any()` or `abort()`, and no `onabort`                                                                                                                                                                                                                                                             |
| `fetch`, `Headers`, `Request`, `Response`                                              | Absolute URLs. A body can't be `FormData` or a stream                                                                                                                                                                                                                                                                          |
| `EventSource`                                                                          | Absolute URLs. Reconnects as a browser's does. Not an `EventTarget`, though it has the same methods                                                                                                                                                                                                                            |
| `WebSocket`                                                                            | Absolute URLs. Only in the apps `ng build --platform` makes. `close()` without a code sends 1000. Not an `EventTarget`, though it has the same methods. On iOS, [cookies, the proxy](/guide/http.md#real-time-with-websockets) and [App Transport Security](/guide/glossary.md#app-transport-security) differ from `fetch()`'s |
| `Blob`, `ReadableStream`, `TextEncoder`, `TextDecoder`, `atob`, `btoa`, `DOMException` | `TextDecoder` decodes UTF-8 only. `ReadableStream` has default readers only                                                                                                                                                                                                                                                    |
| `EventTarget`, `Event`, `CustomEvent`                                                  | `new EventTarget()` and `extends EventTarget`, with the browser's listener options. A target has no parent to pass an event to                                                                                                                                                                                                 |
| `structuredClone()`                                                                    | A buffer in `transfer` is copied, and the original keeps its bytes. Only buffers can be transferred                                                                                                                                                                                                                            |
| `performance.now()`                                                                    | Can jump when the phone's clock changes                                                                                                                                                                                                                                                                                        |
| `crypto.getRandomValues()`, `crypto.randomUUID()`                                      | `getRandomValues()` fills integer arrays only, and is missing in Lynx Explorer. `randomUUID()` isn't cryptographically secure. There's no `crypto.subtle`                                                                                                                                                                      |
| JavaScript built-ins up to ES2025, and `Array.fromAsync()`, `Error.isError()`          | [JavaScript language level](/guide/concepts/javascript-environment.md#javascript-language-level)                                                                                                                                                                                                                               |

## What to keep out of it

These are type errors under the preset. Keep them in the app that has them, or put them behind a service each app provides.

- **The DOM:** `document`, `window`, `navigator`, elements. Lynx's `document` and `window` are stand-ins, not a DOM.
- **Storage:** `localStorage` and `sessionStorage`. Declare an abstract class in the library, and provide it from each app, with `localStorage` on the web and [`LynxLocalStorage`](/guide/persistent-storage.md) on the phone.
- **`FormData`:** Lynx has none.
- **`XMLHttpRequest`:** it exists, but use `HttpClient` or `fetch`.
- **A bare `Uint8Array` as a `Blob` part or a request body:** the DOM's types take only a view of an `ArrayBuffer` there, so type it `Uint8Array<ArrayBuffer>`. `TextEncoder.encode()` returns one.
- **Fetch options Lynx doesn't apply:** `redirect` other than `'follow'`, `mode` other than `'cors'`, and `integrity`. On the phone Lynx's HTTP service follows every redirect, makes no CORS checks and checks no integrity, so a library that counts on them to refuse a response would take it there. `cache`, `credentials`, `keepalive`, `priority`, `referrer` and `referrerPolicy` type-check, since a browser applies them, but don't change the request on a phone. `HttpClient`'s own options of the same names aren't checked: Angular types them as any string. Keep a call that needs one in the web app. If it has to stay in the library and only ever runs on the web, put `// @ts-ignore` with the reason above the option: the web app compiles the same file and accepts the line, so a `// @ts-expect-error` there would be an unused directive, which is an error too.
- **Newer JavaScript the engine can't add:** `new Error(message, { cause })`, resizable `ArrayBuffer`s, `Float16Array` and `Atomics`.

### Storage behind a service

```typescript title="libs/shared/src/key-value-store.ts"
export abstract class KeyValueStore {
  abstract getItem<T>(key: string): Promise<T | null>;
  abstract setItem(key: string, value: unknown): Promise<void>;
}
```

```typescript title="src/app/app.config.ts (AngularLynx app)"
import { LynxLocalStorage } from '@blotch/angular-lynx';
import { KeyValueStore } from 'shared';

export const appConfig = {
  providers: [{ provide: KeyValueStore, useExisting: LynxLocalStorage }],
};
```

The web app provides its own class, which reads and writes `localStorage`.

## What the types can't catch

- **`Intl`.** TypeScript's base library declares it, so the preset can't leave it out, but Lynx has it only when you add it with the [`intl` build option](/guide/i18n/intl.md). Without it, `toLocaleString()` ignores the locale.
- **The `d` and `v` regular expression flags.** TypeScript checks them against your `target`, not `lib`.
- **Error's `cause` through loosely typed arguments.** `new Error(message, { cause })` is a type error, but `new Error(...args)` with `args: any[]` isn't.
- **A global reached by a name built at runtime,** such as `globalThis['fe' + 'tch']` or `globalThis[name]`. See [Added only when used](/guide/concepts/javascript-environment.md#added-only-when-used).

## Use a DOM API on purpose

To type a library against the DOM again, set `lib` and `types` in its own `tsconfig.json`. They replace the preset's:

```json title="libs/shared/tsconfig.json"
{
  "extends": "@blotch/angular-lynx/tsconfig.shared.json",
  "compilerOptions": {
    "lib": ["ES2022", "DOM", "DOM.Iterable", "DOM.AsyncIterable"],
    "types": []
  }
}
```

For one API, keep the preset and leave that code in the app that has it, behind a service the library declares, as with storage above.

## Related

- [The JavaScript environment](/guide/concepts/javascript-environment.md): everything the main thread has, and what's missing
- [HTTP requests](/guide/http.md)
- [Coming from web Angular](/guide/coming-from-web.md)
