Build Your First Angular Website: Lesson 14 of 18

Showing a List of GitHub Users

Up Next

Show a Single User Using Route Parameters

Autoplaying in 7 seconds!

Cancel

We have created our UserService and it is available to our entire application since we registered it in the top-level AppModule.

We can now go into our UserList component and start using it. The steps we'll take are:

  • Inject the UserService
  • Make the call to getUsers() when the component loads
  • Show the users in our UserListComponent's template

Let's get started!

Table of Contents

    Injecting the UserService

    For a component to know to use a specific component, we need to inject it into this component's constructor. This makes it easy to see what a component uses and to be able to test this component in the future.

    We need to import the UserService and also inject into the constructor:

    // src/app/users/users-list.component.ts
    import { Component, OnInit } from '@angular/core';
    import { UserService } from '../../user.service';
    
    @Component({
      // ...
    })
    export class UsersListComponent implements OnInit {
    
      constructor(private userService: UserService) { }
    
      ngOnInit() {
      }
    
    }

    Grabbing Data on Component Load

    Now that we have the userService available in this class, we can start using it. ngOnInit is the place to grab data when a component loads. You may be tempted to use the constructor but refrain from doing so. The constructor is meant to just set up this component and inject dependencies. The ngOnInit method is the specialized place to grab data since it will happen after our component is initialized and has all its dependencies.

    We'll use the userService.getUsers() method we created inside the service.

    ngOnInit() {
      this.userService.getUsers()
        .subscribe(users => {
          console.log(users);
        });
    }

    We are using subscribe because Angular HTTP Client library returns an Observable. This gives us many benefits over Promises that you may be used to when you used .then() instead of .subscribe(). Observables really help with keeping our application reactive. If the users ever change, this observable will automatically update its data!

    We are only subscribing here so we can console.log and see what comes out of this call:

    Now that we know it works, we can rewrite the above to be simpler:

    ngOnInit() { this.users = this.userService.getUsers(); }

    Then we can add a users property to our class so we know what to bind this to:

    export class UsersListComponent implements OnInit {
      users;
    
      constructor(private userService: UserService) { }
    
      ngOnInit() {
        this.users = this.userService.getUsers();
      }
    }

    I really like the ES6 class syntax since you can quickly see:

    • the properties this class has (users)
    • what is required by this class (in the constructor)
    • what happens when this component loads (in ngOnInit)

    Using the Users Data In Our Template

    We have this users property on our class; next up we need to show it in the template. Instead of using .subscribe() inside of our class, Angular provides an easy way to subscribe to the Observable using the async pipe inside our template. Let's demonstrate:

    @Component({
      selector: 'app-users-list',
      template: `
        <div class="card" *ngFor="let user of users | async">
          {{ user.login }} 
        </div>
      `,
      styles: []
    })

    The main line to look at is the template loop using *ngFor. This is how we loop over arrays in our templates.

    The async pipe provides many benefits since the class code is cleaner and also the async pipe will handle .unsubscribe() as well to keep our applications lean.

    Let's add some styling to these. Get ready for Bulma classes galore:

    @Component({
      selector: 'app-users-list',
      template: `
        <section class="section">
        <div class="container">
        <div class="columns is-multiline">
    
          <!-- loop over our users and give them each a card -->
          <div class="column is-4" *ngFor="let user of users | async">
            <div class="card">
              <div class="card-content">
                {{ user.login }} 
              </div>      
            </div>      
          </div>
    
        </div>
        </div>
        </section>
      `,
      styles: []
    })

    Chris Sevilleja

    173 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.