如何使用 Angular 在模块文件中进行 REST 调用
Posted
技术标签:
【中文标题】如何使用 Angular 在模块文件中进行 REST 调用【英文标题】:How to make a REST call in module file with Angular 【发布时间】:2020-09-27 07:25:50 【问题描述】:是否可以在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 中是否有任何本机解决方案或解决方法?
【问题讨论】:
【参考方案1】:您需要在 deps 数组中添加 HttpClient
,以便 Angular 注入它
providers: [
provide: APOLLO_OPTIONS,
useFactory: provideApollo,
deps: [HttpLink,HttpClient],// HttpClient added
,
],
【讨论】:
谢谢,我刚刚尝试了你的实现。我在构造函数constructor(private httpClient: HttpClient)
中做到了这一点,但我得到了 Cannot read property 'httpClient' of undefined
你可以在构造函数中发布你的身体吗?
是的,刚刚更新了答案。我将provideApollo
函数移到了类中,但现在我得到了Cannot find name 'provideApollo'.
哦,对不起,我的错误,你在apollo配置中使用了这个功能,只需撤消所有内容并在deps数组中添加HttpClient,deps:[HttpLink,HttpClient],然后在provideApollo(httpLink: HttpLink, httpClient: HttpClient)...检查它是否有效,我会更新答案以上是关于如何使用 Angular 在模块文件中进行 REST 调用的主要内容,如果未能解决你的问题,请参考以下文章