是否可以在x.module.ts
文件中进行REST调用?
我创建了一个GraphQLModule来与Apollo Client以及该库一起使用,以帮助刷新令牌apollo-link-token-refresh
但是对服务器进行POST
调用时,实现仍然会失败。我尝试将HttpClient
注入函数,但没有成功
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 {}
我找不到试图从模块定义文件进行调用的任何示例。我想我可以尝试安装axios
之类的库,但是在Angular中是否有任何本机解决方案或解决方法?
您可以在GraphQLModule
构造函数中完成此操作
export class GraphQLModule {
constructor(private http: HttpClient) {
console.log(this.http); //do whatever you need here
}
}