使用 Angular 建立簡單 GraphQL client
建立 Angular 專案
$ng new graphql-angular
加入 graphql 套件
$npm install apollo-angular apollo-angular-link-http apollo-client apollo-cache-inmemory graphql-tag graphql --save
修改 app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; import { ApolloModule, Apollo } from 'apollo-angular'; import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http'; import { InMemoryCache } from 'apollo-cache-inmemory'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, ApolloModule, HttpLinkModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { constructor(apollo: Apollo, httpLink: HttpLink) { apollo.create({ link: httpLink.create({ uri: "http://localhost:4000/graphql" }), cache: new InMemoryCache() }) } }
修改 app.component.ts
import { Component } from '@angular/core'; import { Observable } from 'rxjs'; import { map, scan } from 'rxjs/operators'; import { Apollo } from 'apollo-angular'; import gql from 'graphql-tag'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; $users: Observable<User[]>; constructor(apollo: Apollo) { this.$users = apollo.query<any>({ query: gql` { users { id username email } } `}) .pipe( map(res => res.data.users) ) } } interface User { id: String, username: String, email: String }
修改 app.component.html
<div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> <div style="display:flex; justify-content: center;"> <table> <thead> <tr> <td>username</td> <td>email</td> </tr> </thead> <tbody> <tr *ngFor ="let user of $users | async"> <td>{{user.username}}</td> <td>{{user.email}}</td> </tr> </tbody> </table> </div> </div>
執行
npm start -- --port 3800 > [email protected] start /Users/jerryhsieh/Developer/Web/graphql/graphql-angular > ng serve "--port" "3800" Angular Live Development Server is listening on localhost:3800, open your browser on http://localhost:3800/ ** Date: 2018-07-02T07:34:59.681Z Hash: a09b3dec610e50b292e4 Time: 173002ms chunk {main} main.js, main.js.map (main) 13.5 kB [initial] [rendered] chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 227 kB [initial] [rendered] chunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB [entry] [rendered] chunk {styles} styles.js, styles.js.map (styles) 15.6 kB [initial] [rendered] chunk {vendor} vendor.js, vendor.js.map (vendor) 3.62 MB [initial] [rendered] ℹ 「wdm」: Compiled successfully.