Functional resolver with two injected services (Angular 15)

28 views Asked by At

In my resolver, I am trying to inject two services, which uses response of one as input for next service call:

export const addressResolver : ResolveFn<Address> = (
  route: ActivatedRouteSnapshot
) => {

  return inject(UserService).getUserInfo().pipe(
    mergeMap((user: any) => {
      return inject(AddressService).getAddressByUserId(route.params['addressType'], user.id).pipe(
        map((res:any)=>{
           return res;
        }
      ));
    })
  );
};

This code throwing error as

Uncaught (in promise): Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with EnvironmentInjector#runInContext

Can anyone please help what is missing here in this code block. Thanks in advance

1

There are 1 answers

0
Naren Murali On BEST ANSWER

Could you try assigning them to variables and then performing the calls?

export const addressResolver : ResolveFn<Address> = (
  route: ActivatedRouteSnapshot
) => {
  const userServiceInjector = inject(UserService);
  const addressServiceInjector = inject(AddressService);
  return userServiceInjector.getUserInfo().pipe(
    mergeMap((user: any) => {
      return addressServiceInjector.getAddressByUserId(route.params['addressType'], user.id).pipe(
        map((res:any)=>{
           return res;
        }
      ));
    })
  );
};