需求:我们是在一个比较老的项目中Angular8需要restful转化成graphQL
1. 首先直接安装依赖
"apollo-angular": "^4.1.0",
"graphql": "^16.6.0",
"graphql-tag": "^2.12.6",
"@apollo/client": "^3.7.0",
正常应该上面四个依赖就可以使用了,但是因为我的是Angular8,并不支持,会有以下报错
网上查到可能是版本太老,可能需要升级Angular版本,发现升级很麻烦所以放弃了这条解决方式。
现在就找能在Angular8运行的GraphQL包,然后被我找到了。
"apollo-client":"^2.6.0",
"apollo-link":"^1.2.11",
"graphql":"^14.3.1",
"graphql-tag":"^2.10.0",
"apollo-angular":"^1.7.0",
"apollo-angular-link-http":"^1.6.0",
"apollo-cache-inmemory":"^1.3.2",
安装完成这些依赖之后可以进行第二步骤
2. 正常配置graphql配置
- 新建graphql.module模块
import { HttpClientModule } from "@angular/common/http";
import { NgModule } from "@angular/core";
import { InMemoryCache } from "@apollo-cache-inmemory";
import { ApolloModule, APOLLO_OPTIONS } from "apollo-angular";
import { HttpLink,HttpLinkModule } from 'apollo-angular-link-http'
import { environment } from "../../environments/environment";
export function createApollo(httpLink:HttpLink){
return {
link:httpLink.create({uri: environment.graphqlUrl}),
cache:new InMemoryCache()
}
}
@NgModule({
imports:[HttpClientModule,ApolloModule,HttpLinkModule],
providers:[{
provide: APOLLO_OPTIONS,
useFactory:createApollo,
deps:[HttpLink]
}]
})
export class GraphqlModule{}
- 使用query
import gql from "graphql-tag";
export const usersQuery = gql`
query queryAllUsers{
getAllUsers {
age
name
married
}
}
`;
- 引入到app.module.ts中
import {GraphqlModule} from "./apps/graphql/graphql.module";
import {Apollo} from 'apollo-angular'
@ngModule({
imports:[
GraphqlModule
]
)}
- 项目使用
import { Apollo } from "apollo-angular";
import { map, Observable } from "rxjs";
import { usersQuery } from "../graphql/_query/user.query";
@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private readonly apollo: Apollo) { }
getAllUsers(): Observable<User[]> {
return this.apollo.query<GetAllUsers>({ query: usersQuery, fetchPolicy: 'network-only'}).pipe(map(res => {
return res && res.data.getAllUsers;
}))
}
}
完美解决在angular8中使用graphql