Creating a User Service to Connect to GitHub

Usually you would have your own backend API to serve your frontend Angular application some users. Since a backend API isn't the focus for this course, we'll be using GitHub's API. The cool thing about GitHub's API is that you can access it without authentication.

Whenever we want to make calls to get data in Angular, we'll create a service. In this case, I'll call it UserService. You could also call it GitHubService or GitHubUserService (especially if you will create multiple GitHub services for users, repos, etc). It all depends on your application. We'll go with UserService since we're not doing anything too complex.

Use the Angular CLI:

ng g service user

This creates a user.service.ts right in the src/app folder. We'll look at organizing and where we should be putting services that are used across our application. While we could add this to only our UsersModule, I like defaulting services to the top level of our application so that the same service instance is used whenever it is used across our components.

We now have our service. The next step is to get ready to call GitHub's external API. In JavaScript applications, you would use some kind of HTTP library; Axios is the popular one these days in addition to JavaScript's built-in fetch API.

Angular provides it's own HTTP Client library which works really well with the overall Angular framework. It brings helpful tools like easy HTTP interceptors for attaching authentication headers, returning data as Observables, and more.

To start using the HTTP library, we can add it to the main AppModule in the providers array:

import{ Injectable }from'@angular/core';import{ HttpClient }from'@angular/common/http';
@Injectable()exportclassUserService{// define our class properties. apiUrl is what we need// usually you could get this from an environment file
apiUrl ='https://api.github.com/users';// inject the HttpClient as http so we can use it in this classconstructor(private http: HttpClient){}// return what comes back from this http callgetUsers(){returnthis.http.get(`${this.apiUrl}?per_page=10`);}}

Most of this is standard ES6 class functionality. If you're not familiar with classes, this may look a bit foreign to you. We have:

imports at the top

@Injectable decorator to tell Angular that this is going to be a service

export a class called UserService

return an http.get

If you're not familiar with classes, I would recommend browsing some ES6 content on classes and features.