Basic example
The classic example of a counter
What You'll Learn
- How to create a simple service and bind it to your React app
Prerequisites
- Familiarity with Typescript
- Familiarity with Typescript class syntax
The service
Create the new service
First we create the file counter.service.ts
The created service must extend Service
which has been auto-generated in the setup step
export class CounterService extends Service {
}
Service state
Each service has a local state, it is referenced as initialState which must be static
Pass the State
type to the extended Service as Service<State>
type State = { count: number };
export class CounterService extends Service<State> {
static initialState: State = { count: 0 };
}
Append a method
Each method has access to the local state as an observable
To access a local state use its method get
To modify a local state use its method set
type State = { count: number };
export class CounterService extends Service<State> {
static initialState: State = { count: 0 };
increment() {
this.state.count.set((count) => count + 1);
}
}