EmberJS - Router When Promises Reject



The transition will be aborted if a promise is rejected by the model during a transition and there will be no display of new destination route templates and no error message in the console.

Syntax

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

   actions: {
      error: function(reason) {
         // display or return the "Failure Message"
      }
   }
});

Example

The example given below shows how transition will be aborted if model rejects the promise. Create a new route and name it as promisereject and open the router.js file to define the 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('promisereject');
});

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

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

<h2>Router When Promises Reject</h2>
{{#link-to 'promisereject'}}Click Here{{/link-to}}

Now open the promisereject.js file created under app/routes/ with the following code −

import Ember from 'ember';

export default Ember.Route.extend ({
   model: function () {
      //RSVP.js is an implementation of Promises
      return Ember.RSVP.reject("Failure of promises");
   },

   actions: {
      //actions for displaying failure of promises using error hook and it takes 
         reason as parameter
      error: function (reason) {
         document.write("<h3>" + reason + "</h3>");
      }
   }
});

Output

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

Ember.js Reject Promise

When you click on the link, no new route templates will be rendered and it will display a failure message −

Ember.js Reject Promise
emberjs_router.htm
Advertisements