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

317 views Asked by At

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');
};
2

There are 2 answers

0
Jerome On BEST ANSWER
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.

0
Andres2142 On

Make use of the new inject function feature from @angular/core which allows you to inject any dependency you would need, for example, a service

service

interface Hero {
  name: string;
}
@Injectable()
export class HeroService {
  constructor(private http: HttpClient) {}
  getHero(id: string): Observable<any> {
    return this.http.get(...);
  }
}

functional resolver

export const heroResolver: ResolveFn<Hero> =
    (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
      return inject(HeroService).getHero(route.paramMap.get('id')!);
    };

Then access the resolver data from whatever component needs it like the following:

component

@Component({template: ''})
export class HeroDetailComponent {
  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.activatedRoute.data.subscribe(
        ({hero}) => {
            // do something with your resolved data ...
        });
  }
}

I recommend reading the official Angular docs, this example was taken from there.