#Search for users

This is the final feature of our app. We'll start by adding a search box at the top of the users page. Ionic 2 provides a custom searchbar component and that's what we'll use.

src/pages/users/users.html

<!--HTML commented out for brevity-->

<ion-content padding>
  <ion-searchbar></ion-searchbar>
  <ion-list>
    <!--HTML commented out for brevity-->
  </ion-list>
</ion-content>

We've added a search bar with<ion-searchbar>, and should have a searchbar at the top of the page.

The logic behind searching is simple. Since we have a list already, we'll just update the list with our result. The github api enables you to search through the following url structurehttps://api.github.com/search/users?q={searchParam}, with asearchParam.

We'll first of all create a provider method for search in our GithubUsers Provider. The method is also almost similar to theload()method.

src/providers/github-users.ts

// Imports

@Injectable()
export class GithubUsers {
  githubApiUrl = 'https://api.github.com';

  constructor(public http: Http) { }

  // Load all github users
  load(): Observable<User[]> {
    Load Users
  }

  // Get github user by providing login(username)
  loadDetails(login: string): Observable<User> {
    // Load Details
  }

   // Search for github users  
  searchUsers(searchParam: string): Observable<User[]> {
    return this.http.get(`${this.githubApiUrl}/search/users?q=${searchParam}`) 
      .map(res => <User[]>(res.json().items))
  }
}

ThesearchUsersmethod takes in a search parameter, which it will pass to the api url. We then return a Observable of typeUser[](Array of users) like we did initially for theloadmethod.

To test our search method, go to the users page.

src/pages/users/users.ts

// Imports

@Component({
  selector: 'page-users',
  templateUrl: 'users.html'
})
export class UsersPage {
  users: User[]

  constructor(public navCtrl: NavController, private githubUsers: GithubUsers) {
    // Load GithubUsers

    githubUsers
      .searchUsers('scotch').subscribe(users => {
        console.log(users)
      });
  }
  // goToDetails
}

ThegithubUsers.searchUsers('scotch')in the constructor should send a search request to github and return results. Go tohttp://localhost:8100.

Notice that I've circled two of the logins for the results, and they both havescotchin the login property.


We'll only search when three or more characters have been typed.

Let's capture the value typed in from the user in the searchbar.

src/pages/users/user.html

<!-- HTML commented out for brevity -->

<ion-content padding >
  <ion-searchbar (input)="search($event)"></ion-searchbar>
  <ion-list>
    <!-- HTML commented out for brevity -->
  </ion-list>
</ion-content>

We've added an(input)="search($event)"in theion-searchbarto capture the input event for the searchbar. Angular 2 binds to events through(event)syntax.

src/pages/users/users.ts

// Imports commented out for brevity

@Component({
  selector: 'page-users',
  templateUrl: 'users.html'
})
export class UsersPage {
  users: User[]
  originalUsers: User[];

  constructor(public navCtrl: NavController, private githubUsers: GithubUsers) {
    githubUsers.load().subscribe(users => {
      this.users = users;
      this.originalUsers = users;
    })
  }

  goToDetails(login: string) {
    this.navCtrl.push(UserDetailsPage, {login});
  }

  search(searchEvent) {
    let term = searchEvent.target.value
    // We will only perform the search if we have 3 or more characters
    if (term.trim() === '' || term.trim().length < 3) {
      // Load cached users
      this.users = this.originalUsers;
    } else {
      // Get the searched users from github
      this.githubUsers.searchUsers(term).subscribe(users => {
        this.users = users
      });
    }
  }
}

We've added anoriginalUsersclass property, to cache the original results of the github users fetch.

Our search function is structured to only work when the search parameter is of character length that is grater than 3. We reset the results if this condition is not met. (This is not robust however, because the user can enter non-alphanumeric characters, but for learning purposes, will do).

Go tohttp://localhost:8100, and try searching for a term, or a username you know.Clicking any of the result should take you to that user's profile.

results matching ""

    No results matching ""