如何使用 Angular 在模块文件中进行 REST 调用

How to make a REST call in module file with Angular

是否可以在 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 中是否有任何本机解决方案或解决方法?

你需要在 deps 数组中添加 HttpClient,所以 Angular 可以注入它

 providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: provideApollo,
      deps: [HttpLink,HttpClient],// HttpClient added
    },
  ],