createInjectable
Created by Josh Morony Chau Tran
createInjectable
returns a class behind the scenes as a way to
create injectable services and other types of injectables in Angular without using classes and decorators.
The general difference is that rather than using a class, we use a function
to
create the injectable. Whatever the function returns is what will be the
consumable public API of the service, everything else will be private.
providedIn
By default, createInjectable
returns a root service with providedIn: 'root'
. You can override this by passing in a second argument to createInjectable
:
scoped
: The service will be scoped to where it is provided in (i.e:providers
array)platform
: The service will be scoped to the platform (i.e:platform-browser
). This is recommended if you create services that are used across multiple apps on the same platform.
Non-root Service
// defining a serviceexport const MyService = createInjectable( () => { const myState = signal(1); return { myState: myState.asReadonly() }; }, { providedIn: 'scoped' },);
// provide the service{ providers: [MyService];}
// using the serviceconst myService = inject(MyService);
Root Service
// defining a root serviceexport const MyService = createInjectable(() => { const myState = signal(1); return { myState: myState.asReadonly() };});
// using the serviceconst myService = inject(MyService);
Using a named function
It is possible to use a named function as the factory
instead of an arrow function. If a named function is used, the name of the function will be used as the name of the service constructor.
export const MyService = createInjectable(function MyService() { const myState = signal(1); return { myState: myState.asReadonly() };});
console.log(MyService.name); // MyService