1

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 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.