0

Is it possible to do a REST call in the x.module.ts file?

I created a GraphQLModule to work with Apollo Client and also this library that helps refreshing tokens apollo-link-token-refresh

But the implementation keeps failing when making the POST call to the server. I tried injecting the HttpClient into the function without success

import { NgModule } from '@angular/core';
import { HttpClientModule, HttpHeaders } from '@angular/common/http';
import { ApolloModule, Apollo, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { HttpClient } from '@angular/common/http';
import { InMemoryCache, IntrospectionFragmentMatcher} from 'apollo-cache-inmemory';
import { ApolloLink, from } from 'apollo-link';
import { onError } from 'apollo-link-error';
import { TokenRefreshLink } from 'apollo-link-token-refresh';
import * as jwt_decode from 'jwt-decode';

const uri = 'http://localhost:4000/graphql';

export function provideApollo(httpLink: HttpLink, httpClient: HttpClient) {

  ...

  const refreshLink = new TokenRefreshLink({
    accessTokenField: 'accessToken',
    isTokenValidOrUndefined: () => {
      const token = getAccessToken();
      if (!token) {
        return true;
      }

      try {
        const { exp } = jwt_decode(token);
        if (Date.now() > exp * 1000) {
          return false;
        } else {
          return true;
        }
      } catch (error) {
        return false;
      }
    },
    fetchAccessToken: () => {
      return httpClient
        .post(uri, {}, { withCredentials: true })
        .toPromise() as Promise<any>;
    },
    handleFetch: (accessToken: string) => {
      setAccessToken(accessToken);
    },
    handleError: (err: Error) => {
      console.warn('Your refresh token is invalid. Try to relogin');
    },
  }) as any;

  ...

  return {
    link: from([authMiddleware, logoutLink, refreshLink, http]),
    cache
  };
}

@NgModule({
  exports: [ApolloModule, HttpLinkModule, HttpClientModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: provideApollo,
      deps: [HttpLink],
    },
  ],
})
export class GraphQLModule {}

I couldn't find any examples trying to make calls from the module definition file. I guess I could try installing libraries like axios but are there any native solution or workarounds to this in Angular?

1 Answer 1

1

you need to add HttpClient inside the deps array, so Angular could inject it

 providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: provideApollo,
      deps: [HttpLink,HttpClient],// HttpClient added
    },
  ],
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, I just tried your implementation. I did this in the constructor constructor(private httpClient: HttpClient) but I am getting Cannot read property 'httpClient' of undefined
can you post your body inside the constructor?
yeah, just updated the answer. I moved the provideApollo function into the class but now I'm getting Cannot find name 'provideApollo'.
oh, sorry my mistake, you are using this function inside apollo configuration, just undo everything and add HttpClient inside deps array, deps: [HttpLink,HttpClient], and then use it inside provideApollo(httpLink: HttpLink, httpClient: HttpClient)... check if it works and I'll update the answer

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.