Emberjs-routing-prmis-rejct

提供:Dev Guides
移動先:案内検索

EmberJS-約束が拒否された場合のルーター

移行中にモデルによってプロミスが拒否された場合、移行は中止され、新しい宛先ルートテンプレートの表示もコンソールのエラーメッセージも表示されません。

構文

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

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

以下の例は、モデルがプロミスを拒否した場合に移行が中止される方法を示しています。 新しいルートを作成し、_promisereject_という名前を付け、_router.js_ファイルを開いてURLマッピングを定義します-

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;

次のコードで_app/templates/_の下に作成されたファイル_application.hbs_ファイルを開きます-

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

今、次のコードで_app/routes/_の下に作成された_promisereject.js_ファイルを開きます-

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>");
      }
   }
});

出力

エンバーサーバーを実行すると、次の出力が表示されます-

Ember.js Reject Promise

リンクをクリックすると、新しいルートテンプレートはレンダリングされず、エラーメッセージが表示されます-

Ember.js Reject Promise