Sometimes, it’s not necessary to add huge store libraries in an Angular application. All we need is RxJs library which provides observables and operators. In the article we will figure out how to create a state management from scratch using Subject and Observables on the example of the recipe finder Angular application.

What’s the problem?

We have several components or, even, modules around the application which use the same data. How to provide and update this data easily? Where should we keep it?

Mr. Store is hurrying to help!

Defining the Store

Let’s create a separate service where we want to save everything we can use in any component of the project. Also, we would like to take any values from our Store and, furthermore, subscribe to any changes.

export interface Store {
  recipes: Recipe[];
  savedRecipes: Set<Recipe>;
}
@Injectable({
  providedIn: 'root',
})
export class StoreService {
  private store: BehaviorSubject<Store>;

  constructor() {
    this.store = new BehaviorSubject<Store>({
      recipes: [],
      savedRecipes: new Set<Recipe>()
    });
  }
}

#state #rxjs #javascript #angular

Not always you need a state management library-How to build your own simple Store use RxJs
1.55 GEEK