angularhttprequestget-requestangular-resolver

How do I run a http request using a functional resolver?


In the past I can use a class based resolver where I can inject HttpClient in the constructor, but that's been deprecated Source.

I'd like to make an HTTP get request in a functional resolver. How do I inject an HTTP client?

Here's my resolver code:

import { ResolveFn } from '@angular/router';

export const chuckResolver: ResolveFn<boolean> = (route, state) => {
  return this.http.get<any>('https://api.chucknorris.io/jokes/random');
};

Solution

  • import { ResolveFn } from '@angular/router';
    import { inject } from '@angular/core';
    
    export const chuckResolver: ResolveFn<boolean> = (route, state) => {
    
        const http = inject(HttpClient);
    
        return http.get<any>('https://api.chucknorris.io/jokes/random');
    };
    

    N.B. User @j4rey posted this as an answer which is what worked for me but he deleted it. So I'm posting it myself.