EmberJS – Loading/Error Substates

error and loading

The Ember.js overrides transitions for customizing asynchronization between the routes by making use of error and loading substates.

Syntax

Ember.Route.extend ({
   model() {
      //code here
   }
});

Router.map(function() {
   this.route('path1', function() {
      this.route('path2');
   });
});

Example

The example given below demonstrates the use of Loading / Error Substates which occurs while loading a route. Create a new route and name it as loaderror and open the router.js file with the following code to define URL mappings −

import Ember from 'ember';                   
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config 

//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});

//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('loaderror', function() {
      this.route('loaderr');
   });
});

//It specifies Router variable available to other parts of the app
export default Router; 

Open the file loaderror.js file created under app/routes/ with the following code −

import Ember from 'ember';

export default Ember.Route.extend ({
   model() {
      return new Ember.RSVP.Promise(function (resolve, reject) {
         setTimeout(function () {
            resolve({});
         }, 1500);
      });
   }
});

Open the file application.hbs created under app/templates/ with the following code −

{{outlet}}

Open the file index.hbs and add the following code −

{{link-to 'loaderror' 'loaderror'}} 
<small>(this link displays the 'loading' route/template correctly)</small>
{{outlet}}

When you click on the loaderror link, the page should open with the loading state. Therefore, create a loading.hbs file to specify the loading state −

<h2 style = "color: #f00;">template: loading</h2>

Now open the loaderror.hbs file that displays the error message −

<h2>--error--!</h2>
{{link-to 'loaderror.loaderr' 'loaderror.loaderr'}} 
<small>(doesn't display the 'loading' route/template, 
   because 'loaderror/loading' does not exist!!!</small>
{{outlet}}

Output

Run the ember server and you will receive the following output −

error and loading

When you click on the link, it will show the template loading message −

Then it displays an error substate when errors are encountered during a transition −

error and loading

Previous Page:-Click Here

Leave a Reply