Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Request: Need Recommendation for DI #33

Closed
dapperdandev opened this issue Oct 28, 2021 · 2 comments
Closed

Support Request: Need Recommendation for DI #33

dapperdandev opened this issue Oct 28, 2021 · 2 comments

Comments

@dapperdandev
Copy link

dapperdandev commented Oct 28, 2021

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[x] Support request
[ ] Other... Please describe:

Current behavior

Currently, there is no clear way to inject services/tokens for use with rtk-query.

Expected behavior

I would like to inject HttpClient for use as a custom query function. The sample code below intends to use fetchFn, but that may not be the actual solution. The only problem I'm trying to solve is providing HttpClient, then using that for network requests.

Minimal reproduction of the problem with instructions

// features.api.ts
import { createApi } from 'ngrx-rtk-query';
import { configureBaseQuery } from '@app/shared/data-access/+store';

export const featuresApiKey = 'featuresCache';
const cacheTags = {
    enabledFeatures: 'enabledFeatures'
};

export const featuresApi = createApi({
    reducerPath: featuresApiKey,
    tagTypes: Object.values(cacheTags),
    baseQuery: configureBaseQuery('/api'),
    endpoints: (build) => ({
        getEnabledFeatures: build.query<Array<string>, string>({
            query: (organizationId) => ({
                url: `/organizations/${organizationId}/features`
            })
        })
    })
});

export const { useGetEnabledFeaturesQuery } = featuresApi;
// configure-base-query.ts
export const configureBaseQuery = (endpointUrl: string, maxRetries: number = 0): BaseQueryFn => {
    return retry(
        fetchBaseQuery({
            // fetchFn: httpClient, 
            baseUrl: `${endpointUrl}`,
            prepareHeaders: (headers: Headers, api) => {...}
        }),
        { maxRetries }
    );
};

What is the motivation / use case for changing the behavior?

We sometimes use angular services rather than rtk-query for network requests. We want our HttpInterceptors to work for both rtk-query and angular services.

Environment


Angular version: 12.2.0


Browser:
- [ ] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [x] Edge version 95.0.1020.30
@SaulMoro
Copy link
Owner

SaulMoro commented Oct 28, 2021

Remember that baseQuery is designed to return promises: https://redux-toolkit.js.org/rtk-query/api/createApi#basequery

Thanks to using RTK Query, I have been able to remove the need for HttpClient (since you can use RTK Query functions as an interceptor if necessary). But if you need to use it, you can try something like the following:

  1. In app.component or APP_INITIALIZER
import { Injector, NgModule } from '@angular/core';

export let AppInjector: Injector;
    
export class AppModule {
      constructor(private injector: Injector) {
         AppInjector = this.injector;
      }
}

You can export the AppInjector variable from another source

  1. In customBaseQuery / queryFn file
import {AppInjector} from '../app.module';

const httpClient = AppInjector.get(HttpClient); // or AppInjector.get(MyService);

Later in baseQuery, you must act according to the method (Get, Post, ...). You can look at the axios example: https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#axios-basequery

If you make it work, can you share it? I can create a httpClientBaseQuery utility for the library

@dapperdandev
Copy link
Author

dapperdandev commented Nov 4, 2021

@SaulMoro Thanks for the response. I haven't had a chance to circle back to this yet. We've decided to move forward by putting interceptor logic somewhere that both angular interceptors and rtk middlewares can use.

I like the injector idea, but we have to jump through a few hoops to ensure we don't end up with circular dependencies. Especially with Nx. I'm still interested in giving that a shot though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants