concept user in category aurelia

appears as: users, user, User, The user, users, A user
Aurelia in Action

This is an excerpt from Manning's book Aurelia in Action.

  • Aurelia provides routing to allow developers to build SPAs that feel like real websites, supporting the standard web-interaction patterns that users are familiar with.
  • Traditional request/response applications load the entire page for each request. To illustrate this, imagine you want to implement the my-books website using the server-side routing model (we’ll call this Scenario 1). In this case, the initial page request returns the index.html page as the response. Then, when the user clicks a link through to the /books URL, the browser sends another request to the server, which then returns the HTML (and data) representing the book-management page.

    In the case of an SPA (Scenario 2), when the user initially navigates to the my-books site, the browser makes a request to the server to retrieve the index.html file (the same as Scenario 1). When the user clicks the /books anchor tag, however, the SPA router (Aurelia’s routing module) determines which component should be rendered into the DOM and replaces the contents of the application shell with a component. The application shell is the container with common elements that you want to remain consistent across every page of your SPA. The differences between these scenarios are depicted in figure 9.1.

    Figure 9.1. The differences between the request/response routing model and the SPA routing model

    The alternative to using client-side routing is to update the content inside the application without maintaining a history of these state changes using the router. For example, in Scenario 2 you’d still have an application shell that you could then use to slot in various components as the user moves between different application states. The question is, what benefits do you get from introducing client-side routing? It has two main benefits:

    Listing 9.5. Creating a new user-api service class (user-api.js)
    import {HttpClient, json} from 'aurelia-fetch-client';
    import {inject} from 'aurelia-framework';
    
    @inject(HttpClient)
    export class UserApi{
    
        constructor(http){
            this.http = http;
    
            const baseUrl = 'http://localhost:8333/api/';         #1
    
            http.configure(config => {
                config.withBaseUrl(baseUrl);
            });
        }
    
         getUser(name){
            return this.http.fetch(`users/${name}`)               #2
                     .then(response => response.json())
                     .then(user => {
                        return user;
                     })
                    .catch(error => {
                        console.log('Error retrieving user.');
                    });
    
        }
    
        getUsers(){
    
            return this.http.fetch('users')                       #3
                     .then(response => response.json())
                     .then(users => {
                        return users;
                     })
                    .catch(error => {
                        console.log('Error retrieving users.');
                    });
    
        }
    
        addUser(user){
            return this.http.fetch('users', {                     #4
                method: 'post',
                body: json(user)
                })
                .then(response => response.json())
                .then(createdUser => {
                    return createdUser;
                })
                .catch(error => {
                    console.log('Error adding user');
                });
        }
    
        deleteUser(user){                                        #5
            return this.http.fetch(`users/${user.name}`, {
                    method: 'delete'
                    })
                    .then(response => response.json())
                    .then(responseMessage => {
                        return responseMessage;
                    })
                    .catch(error => {
                        console.log('Error deleting book');
                    });
        }
    
        saveUser(user){
            return this.http.fetch(`users/${user.name}`, {       #6
                        method: 'put',
                        body: json(user)
                     })
                     .then(response => response.json())
                     .then(savedUser => {
                        return savedUser;
                     })
                    .catch(error => {
                        console.log('Error saving book');
                    });
        }
    }
    

    The user component should look familiar to you. You’ll create a new custom element by creating a new view/view-model pair. The view-model retrieves the list of users via the UserApi service class, which is then bound to the view and rendered into a table using a templating repeater. Create a new JavaScript file at ./src/resources/elements/users.js and enter the contents of the following listing.

    Listing 9.6. Adding the users view-model (users.js)
    import {bindable, inject} from 'aurelia-framework';
    import {UserApi} from '../../services/user-api';
    
    @inject(UserApi)
    export class Users{
        constructor(userApi){
            this.userApi = userApi;                    #1
        }
    
        bind(){
            this.loadUsers();                          #2
        }
    
        loadUsers(){
            this.userApi.getUsers().then(users => {
                this.users = users;                    #3
            });
        }
    }
    

    Then, create the corresponding view file to display basic user information in a table. Each row in the table includes an Edit button to allow users to click through and view more-detailed user information. This is achieved by using a route-href custom attribute. This attribute takes a binding expression that includes the route that should be used to calculate the URL value (user-detail) and any parameters that should be passed to the route calculation (user.name). Create a new HTML file at ./src/resources/elements/users.html and add the contents of the following listing.

    Listing 9.7. Adding the users view (users.html)
    <template>
        <require from="./heading.html"></require>
        <heading text.bind="'users'"></heading>
    
        <div class="card">
            <table show.bind="users"
                   class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <tr repeat.for="user of users">
                        <td>${user.name}</td>
                        <td>${user.email}</td>
                        <td>
                            <a class="btn btn-secondary"
           route-href="route: user-detail;                    #1
           params.bind: {name:user.name}" >
                                  details
                            </a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </template>
    

    The user-details component is responsible for retrieving a user by name from the UserApi service and rendering details to a form on the view. The name of the user is pulled from the params array, which is passed to the activate-routing-lifecycle callback, activate(params, routeConfig) {... }. We’ll cover the routing lifecycle in section 9.5. Create the user-details view-model file at ./src/resources/elements/user-details.js and add the contents of the following listing.

    Listing 9.8. Adding the user-details view-model (user-details.js)
    import {bindable, inject} from 'aurelia-framework';
    import {UserApi} from '../../services/user-api';
    
    @inject(UserApi)
    export class UserDetails{
    
        constructor(userApi){
            this.userApi = userApi;
        }
    
        activate(params, routeConfig) {             #1
            this.loadUser(params.name);
        }
    
        loadUser(name){
            this.userApi.getUser(name).then(fetchedUser => {
                this.user = fetchedUser;
            });
        }
    
        saveUser(){
            this.userApi.saveUser(this.user).then(savedUser => {
                alert('Successfully saved user');
            });
        }
    }
    

    Create the corresponding user-details view file at ./src/resources/elements/user-details.html, as shown in the following listing. This is effectively a form that allows users to view and edit user information.

    Listing 9.9. Adding the user-details view (user-details.html)
    <template>
        <form if.bind="user" class="form card" submit.trigger="saveUser()">
            <div class="card-block">
                <h4 class="card-title">User details
                    <i class="fa fa-user" ></i></h4>
                <h6 class="card-subtitle mb-2 text-muted">
                    view / edit user details</h6>
                <hr/>
                <div class="form-group">
                    <label for="name">Name</label>
                    <input readonly
                            name="name" class="form-control"
                            placeholder='enter a name'
                            value.bind="user.name">
                    </input>
                    <label for="first_name">First Name</label>
                    <input name="first_name" class="form-control"
                            placeholder='enter first name'
                            value.bind="user.first_name">
                    </input>
                    <label for="surname">Surname</label>
                    <input name="surname" class="form-control"
                            placeholder='enter a surname'
                            value.bind="user.surname">
                    </input>
                    <label for="email">Email</label>
                    <input name="email" class="form-control"
                            placeholder='enter an email address'
                            value.bind="user.email">
                    </input>
                </div>
            </div>
            <div class="card-footer">
                <a class="btn btn-secondary col-sm-2"
       route-href="route: users" >
                    <i class="fa fa-arrow-left"></i> back
                </a>
                <button type="submit" class="btn btn-primary
       col-sm-2 push-sm-8"
                        disabled.bind="user.name.length == 0">
                    save
                </button>
            </div>
        </form>
    </template>

    With the required files in place, the last step is to add the two new routes representing the users and user-details views. The users route uses a basic route configuration, as you saw with the books and index views. The user-details route, however, uses a parameterized route, 'users/:name/details', which allows you to then pass along the username in the query string to deep link to the given user that takes a URL like http://localhost:9000/#/users/Bilbo/details. A user of the my-books application could bookmark or refresh this page and still get the same page state.

    A note on terminology. In Aurelia, a screen is the name for a navigable component. For example, the users, user-details, and books components in the my-books application are screens but the edit-book component isn’t.

  • A user-management section that uses route parameters to allow deep linking to users by name