Dan Nisenson
Dan Nisenson

Reputation: 21

Angular async signal state management

I'm working on a medium sized Angular app and this is the situation:

  1. The user gets auth'd and data A is requested. Once/if that comes through, data B must be requested. Data A is global. Data B is specific to the page, but still has to be persistant.
  2. Data A includes the default/available date range. User must be able to input date range.

Component:

@Component({
  selector: 'app-example',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './example.component.html',
})
export class ExampleComponent {
  myService = inject(MyServiceService);

  waitForA = effect(
    () => this.myService.availableDates() && this.myService.requestDataB(), 
    {allowSignalWrites: true}
);

  handleSelectDates(dates: Dates) {
    this.myService.selectedDates.set(dates);
  }
}

Service:

@Injectable({
  providedIn: 'root'
})
export class ExampleService {
  #http = inject(HttpClient)
  #someOtherService = inject(SomeOtherServiceService)

  exampleState = signal({state: []})
  selectedDates = signal(start: null, end: null})

  availableDates = computed(() => this.#someOtherService.dataAdates())

  #setInitDates = effect(
    () => 
      this.availableDates() && this.selectedDates.set(this.availableDates()),
    { allowSignalWrites: true }
  );

  requestData() {
    this.#http.get('url').subscribe(data => this.exampleState.set({state: data}))
  }
}

I know the Angular team advises against the use of {allowSignalWrites: true} but any other way I can think of even using rxjs, storing the response to the service would be a side-effect, like:

waitForA = toObservable(this.myService.availableDates())
  .subscribe(dates => dates && this.myService.requestDataB()
);

Upvotes: 0

Views: 381

Answers (0)

Related Questions