安装
1.with angular-cli
先创建angular项目,否则会出现如下错误:
1
| The add command requires to be run in an Angular project, but a project definition could not be found.
|
1 2 3
| ng new graphGL-demo
ng add apollo-angular
|
修改文件 src/app/graphql.module.ts
//our test Graphql Server which returns rates
1
| const uri = 'https://o5x5jzoo7z.sse.codesandbox.io/graphql';
|
本文基于angular-cli已安装进行介绍
2.without angular-cli
1 2 3 4 5 6 7
| npm install --save apollo-angular \ apollo-angular-link-http \ apollo-link \ apollo-client \ apollo-cache-inmemory \ graphql-tag \ graphql
|
hello-world
创建新组建
1
| ng g component hello-world
|
添加graphql引用组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| rates: any[]; loading = true; error: any;
constructor(private apollo: Apollo) {}
ngOnInit() { this.apollo .watchQuery({ query: gql` { rates(currency: "USD") { currency rate } } `, }) .valueChanges.subscribe((result:any) => { this.rates = result.data && result.data.rates; this.loading = result.loading; this.error = result.error; }); }
|
添加graphql html
1 2 3 4 5 6 7 8 9 10 11
| <div *ngIf="loading"> Loading... </div> <div *ngIf="error"> Error :( </div> <div *ngIf="rates"> <div *ngFor="let rate of rates"> <p>{{rate.currency}}: {{rate.rate}}</p> </div> </div>
|
参考
本文作者:前端analysis
版权声明: 本文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏