获取Github用户
We'll create a service for getting Github users fromhttps://api.github.com/users
. The page lists about 30 of the first github users in json format.
First, we need to create a Github user model. This is a class that holds the relevant fields we want for a github user, since github offers a lot of details.
Create a folder calledmodelsin thesrcfolder. This is where we will put our User model and other models we may wish to create later on. Insidesrc/modelsand add a fileuser.ts.
src/models/user.ts
// User model based on the structure of github api at
// https://api.github.com/users/{username}
export interface User {
login: string;
avatar_url: string;
public_repos: number;
public_gists: number;
followers: number;
following: number;
}
We've only included properties we'll need from a github response. Now that we have our model defined, we can create a github-users provider to enable us pull the users from github. To generate a provider run the following in your terminal
$ ionic g provider github-users
This creates a folder calledprovidersin thesrcdirectory, and agithub-users.tsfile.
We need to add a method to get github users in the generatedgithub-users.tsfile.
We'll slightly modify the generatedsrc/providers/github-users.tsfile
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { User } from '../models/user';
@Injectable()
export class GithubUsers {
githubApiUrl = 'https://api.github.com';
constructor(public http: Http) { }
// Load all github users
load(): Observable<User[]> {
return this.http.get(`${this.githubApiUrl}/users`)
.map(res => <User[]>res.json());
}
}
The@Injectable()
decorator is how Angular 2 declares it's services/providers.
TheObservable
import is necessary for because we will return the results of the github API call as an observable. Think of an observable as a stream of data we can subscribe to. We'll look at this in a bit more details shortly.
The first thing we did was to import the user model withimport {User} from '../models/user'
.
Then we add a functionload
which will return an Observable
We make a request to the github api, and parse the json response withres.json()
, which we then cast as an array of users with<User[]>res.json()
. This is returned as an observable, which we'll subscribe to to see the users.
To use our service in the whole app, we need to add it to thesrc/app/app.module.tsfile.
// Imports commnted out for brevity
import { GithubUsers } from '../providers/github-users';
@NgModule({
declarations: [
// Declarations commented out for brevity
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
// Entry Components commented out for brevity
],
providers: [GithubUsers] // Add GithubUsers provider
})
export class AppModule {}
We simply import the GithubUsers and add it in theproviders_property of the_NgModule.