Angular 4 和 GitHub GraphQL API

Angular 4 and GitHub GraphQL API

此刻我有这样的东西

return this._http.get('https://api.github.com/users/' + this.username + '/repos?client_id=' + this.client_id + '&client_secret=' + this.client_secret)
.map(res => res.json());

获取所选用户的存储库列表(不使用 GraphQL)。

除了使用 GraphQL 之外,我如何才能获得问题列表? 这是 grom GitHub API 文档的示例:

query {
  repository(owner:"octocat", name:"Hello-World") {
    issues(last:20, states:CLOSED) {
      edges {
        node {
          title
          url
          labels(first:5) {
            edges {
              node {
                name
              }
            }
          }
        }
      }
    }
  }
}

如何在 Angular 4 中实现它?

至少有两种方式:

  • 使用像 apollo-angular
  • 这样的 GraphQL 客户端
  • 使用简单的 HTTP 请求从 GraphQL API 获取数据

使用 HTTP

const query = `query {
  repository(owner:"octocat", name:"Hello-World") {
    issues(last:20, states:CLOSED) {
      edges {
        node {
          title
          url
          labels(first:5) {
            edges {
              node {
                name
              }
            }
          }
        }
      }
    }
  }
}`;

this._http.get(LINK_TO_API + '?query=' + query);

使用apollo-angular

https://github.com/apollographql/apollo-angular

Apollo 是一个 GraphQL 客户端。

这是文档:

http://dev.apollodata.com/angular2/

一个例子:

import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';

@Component({
    /* ... */
})
class UsersComponent implements OnInit {

    constructor(
        private apollo: Apollo
    ) {}

    ngOnInit() {
        // or this.apollo.watchQuery() - read the docs
        this.apollo.query({
            query: gql`
                {
                    repository(owner: "octocat", name: "Hello-World") {
                        issues(last:20, states:CLOSED) {
                            edges {
                                node {
                                    title
                                    url
                                    labels(first:5) {
                                        edges {
                                            node {
                                                name
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            `
        }).subscribe(response => {
            console.log('data', response.data);
        });
    }
}

一个工作示例:

https://github.com/kamilkisiela/apollo-angular-reproduction/blob/master/client/app/post/post-list.component.ts

https://github.com/apollographql/githunt-angular