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?
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
},
],