Search code examples
angularangular-resolver

How does the Angular resolver handle subscriptions?


I am using an Angular resolver to load initial Data of my page. As known it is possible to either return an observable or a promise.

In my case I have this:

export class MySiteResolver implements Resolve<ApiResponse> {
    readonly #myApiService = inject(MyApiService);

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<ApiResponse> {
        const param = Number(route.paramMap.get("param"));
        return this.#myApiService.getMethod(param);
    }
}

As expected when loading the page, the resolver subscribes to the observable and return the Api results.

Now I have two questions:

  • Does the resolver keep the subscription alive? or does it take only the first/last result of my api call?
  • If the subscription stays alive, does it unsubscribe to it after changing the route?

Or just in general, how does it handle the subscription?

I looked up to figure out an answer, but I couldn't really find anything in the Angular documentations, neither in related questions in stackoverflow. I definitely could take the safe way and either return a promise or use the first() operator. However I insist on figuring out how Angular handles it.

I appreciate any insights. Thank you for your time!


Solution

  • They use the rxjs property takeLast(1), so this does two things.

    1. Takes the last emission after observable completes.
    2. When observable is completed, the subscribers are also completed meaning there is no memory leak.
    3. Http requests are auto completing once the API call is done.

    resolve-data.ts - source code