5.4: Retrieving Users from the Database

Adding Our API's Base Url to Environment Config

Currently, we only have one service, our AuthService. It's storing our base API URL as a hard-coded string.

As we add other services, it will be easier to have this in our configuration. If we need to make changes (for example, deployment) it will be easier to change it in one location.

Open up the environment.ts file inside of the environments folder and update it to include the apiUrl:

export const environment = {
  production: false,
  apiUrl: 'http://localhost:5000/api/'      // <--- Added
};

Now, we can update our AuthService class to use this endpoint instead of the one hard-coded:

baseUrl = environment.apiUrl;

Update the login() and register() methods to access the appropriate endpoint (by adding /auth/):

login(model: any) {
    return this._http.post<AuthUser>(this.baseUrl + 'auth/login', model, { headers: new HttpHeaders()          //    modified
      .set('Content-Type', 'application/json') })
      .map(user => {
        if (user) {
          localStorage.setItem('token', user.tokenString);
          this.decodedToken = this._jwtHelperService.decodeToken(user.tokenString);
          this.userToken = user.tokenString;
        }
      });
  }

  register(model: any) {
    return this._http.post(this.baseUrl + 'auth/register', model, { headers: new HttpHeaders()                 //    modified
      .set('Content-Type', 'application/json')
    });
  }

Adding a User Service

In the root of your SPA application, run the following command to generate a new UserService:

ng g s /services/user --no-spec

Update the newly generated service to the following:

export class UserService {

  baseUrl = environment.apiUrl;

  constructor(
    private _http: HttpClient,
    private _authService: AuthService,
    private _jwtHelperService: JwtHelperService) { }

  getUsers(): Observable<User[]> {
    return this._http.get<User[]>(this.baseUrl + 'users', { headers: new HttpHeaders()
      .set('Authorization', `Bearer ` + this._authService.decodedToken) });
  }

}

Make sure that the UserService is imported and in the providers array in your app.module.ts file (CLI doesn't automatically add it for some reason):

import { UserService } from './services/user.service';

//  ...

providers: [
    AuthService,
    UserService,
    AuthGuard
  ],

Display Users in the MemberListComponent

Now, let's display our Users in our MemberListComponent.

Open up member-list.component.ts and add this code:

export class MemberListComponent implements OnInit {

  users: User[];

  constructor(private _userService: UserService) { }

  ngOnInit() {
    this.loadUsers();
  }

  loadUsers() {
    this._userService.getUsers().subscribe((users: User[]) => {
      this.users = users;
    }, error => {
      console.log('Failed to load users.');
    });
  }

}

Now, let's use this in our template to display them.

Add the following to member-list.component.html.

We'll improve this shortly, but for now let's test to make sure our service is set up correctly and getting data from our backend.

When you login as a user, you should see an ugly list of the names of our users.

Last updated