#Should I return an Observable in my resolver?

5 messages · Page 1 of 1 (latest)

pseudo plaza
#

Simple as that, I made this resolver and I was wondering if it's better to return an Observable<Person>

export const personResolver: ResolveFn<Person | null> = (route, state) => {
  const id = route.paramMap.get('id')!;
  const personService = inject(PersonService);
  let person: Person | null = null;

  personService.getPersonById(id).subscribe({
    next: (data) => {
      person = data;
    },
    error: (err: HttpErrorResponse) => {
      // TODO: handle
    },
  });

  return person;
};
#

because if I don't return an Observable it's harder to handle error/loading logic, right?

hard pond
#

You should return an Observable in this case, yes.
In fact, generally you should not subscribe in a resolver at all. Your current code is completely broken. The resolver will always return null, because it returns, before the Observable ever emits a value (unless getPersonById emits synchronously, which is very rare). Additionally, this resolver is now leaking a subscription.

You should return an Observable and Angular will handle it for you. But do note that it will delay navigation until your Observable emits.

pseudo plaza
#

Right, and then in the component I handle it like this?

protected person = signal<Person>(this.route.snapshot.data['person']);
hard pond
#

No, that doesn't handle the situation where the data changes.
You have to subscribe in the component. I personally recommend using withComponentInputBinding and using an input signal. If you don't want that, you can use toSignal to subscribe to the route data.