BehaviorSubject — Angular

Angular app state management with BehaviorSubjects.

Sometimes you do not need a state management library like NGRX to manage your Angular app state.

// myFormsService.service.tsimport { Injectable } from '@angular/core';
import { BehaviourSubject } from 'rxjs/BehaviourSubject';
import { myInterfaceInit1, IForm1 } from './models/myInterfaceInit1';
import { myInterfaceInit2 , IForm2} from './models/myInterfaceInit2';
@Injectable()
export class MyFormsService{
// Initializer the BehaviorSubject with default values for your form component model
private form1State = new BehaviorSubject(myInterfaceInit1);
private form2State = new BehaviorSubject(myInterfaceInit2);
setForm1State(form1State): void {
this.form1State.next(form1State);
}
getForm1State(): IForm1 {
return this.form1State.value;
}
setForm2State(form2State): void {
this.form2State.next(form2State);
}
getForm2State(): IForm1 {
return this.form2State.value;
}
}
import { NgModule } from '@angular/core';
import { MyFormsService } from './myFormsService';
@NgModule({ // can be a component otherwise or another service
.....
provider:[ MyFormsService ] //provider for our service to components
.....
})
// componentForm1.component.ts@import { Component, OnInit } from '@angular/core';
@import { MyFormsService } from './myFormsService';
@import { myInterfaceInit1, IForm1 } from './models/myInterfaceInit1';
@Component({...})
export class ComponentForm1 implements OnInit {
form1Model:IForm1 = myInterfaceInit1;

constructor(private myFormsService: MyFormsService){}
ngOnInit(): void {
//this allow you to display the values ofthe form when the component is navigated to
this.form1Model = this.myFormsService.getForm1State();
}
goToOtherForm(): void {
// this will set the values from the form model to our behavior subject
this.myFormsService.setForm1State(this.form1Model)
}
...
@import { MyFormsService } from './myFormsService';
....
@Component({...})
.....
// the following method will be called when a button is (clicked) in the components form templategatherAndSubmitData(): void {
const dataFromForm1 = this.myFormsService.getForm1State();
const dataFromFormX = this.myFormsService.getFormXState();
// create POST objectconst data = {
dataFromForm1,
dataFromFormX
}
// call service for http requests and pass body object

Final thoughts….

Stargazer