当前位置: 首页 > 文档资料 > EmberJS 入门教程 >

当Promises拒绝(When Promises Reject)

优质
小牛编辑
134浏览
2023-12-01

如果在转换期间模型拒绝承诺,则将中止转换,并且不会在控制台中显示新的目标路由模板和错误消息。

语法 (Syntax)

Ember.Route.extend ({
   model() {
      //code here
   },
   actions: {
      error: function(reason) {
         // display or return the "Failure Message"
      }
   }
});

例子 (Example)

下面给出的示例显示了如果模型拒绝承诺,将如何中止转换。 创建一个新路由并将其命名为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>");
      }
   }
});

输出 (Output)

运行ember服务器,您将收到以下输出 -

Ember.js拒绝承诺

当您单击链接时,将不会呈现新的路径模板,它将显示失败消息 -

Ember.js拒绝承诺